How can i re-render observable array-data in Mobx? I used observer decorator in this class.
interface IQuiz {
quizProg: TypeQuizProg;
qidx: number;
state: IStateCtx;
actions: IActionsCtx;
}
@observer
class Comp extends React.Component<IQuiz> {
private _qtype: common.TypeQuiz = '';
private _qtime = 60;
@observable _quizs: common.IQuizData[] = [];
constructor(props: IQuiz) {
super(props);
makeObservable(this);
};
public componentWillMount() {
this._quizs = this.props.actions.getData();
}
@action
public quizSelect(idx: number, v: boolean) {
this._quizs[idx].selected = true;
this._quizs.slice();
}
public render() {
const {state, actions, qidx} = this.props;
let ItemComponent;
if(this._qtype === 'unscramble') ItemComponent = QuizUnscramble;
if(this.props.state.prog !== 'quiz') {
return <QuizList
state={state}
quizs={this._quizs}
quizSelect={(idx: number, v: boolean) => {
this.quizSelect(idx, v);
}}
/>
} else {
return (
<QuizBox
view={true}
className="t_quiz"
quizProg={state.quizProg}
qidx={qidx}
qtype={this._qtype}
qtime={this._qtime}
quizs={this._quizs}
ItemComponent={ItemComponent}
isteacher={false}
setQuizProg={actions.setQuizProg}
/>
);
}
}
}
const Quiz = useTeacher((store: TeacherContext) => (
<Observer>{() => (
<Comp
quizProg={store.state.quizProg}
qidx={store.state.qidx}
state={store.state}
actions={store.actions}
/>
)}</Observer>
));
I use mobx6 and react-typeacript. Comp class dosen't re-rendering when i run quizSelect function. Do not check mobx observable data point of different deeply? @observable.deep is not working too.
How can i fix it?
CodePudding user response:
I believe the problem lies in the componentWillMount
method where you're overwriting the original array which you've marked observable
. Things like arrays and objects are handled a bit differently since they are reference types and not value types.
Pushing the elements into the existing array rather than reassignment should fix the issue:
public componentWillMount() {
this._quizs.push(...this.props.actions.getData());
}
CodePudding user response:
I found answer. Reference type need reallocation.
this._quizs[idx].selected = v;
this._quizs = _.cloneDeep(this._quizs);