[英]Mobx not updating when state changes
I am using react-table with mbox and have run into a issue where my state is not updating. 我在mbox上使用react-table,遇到了状态不更新的问题。
I have a table like this 我有这样的桌子
<ReactTable
data={data}
columns={columns}
showPageSizeOptions={false}
resizable={false}
className="-striped -highlight"
defaultPageSize={12}
filterable={true}
/>
A column that has 具有以下内容的列
{
Header: "",
accessor: "checkbox",
filterable: false,
width: 35,
Cell: ({ original }) => {
return (
<input
type="checkbox"
className="checkbox"
checked={employeeUiStore.selectedEmployees.indexOf(original.id) >= 0 }
onChange={() => employeeUiStore.toggleCheckbox(original.id)}
/>
);
}
},
and a store like this 和像这样的商店
class EmployeeUiStore {
@observable addMode = false;
@observable selectedEmployees = []
constructor(){}
@action
toggleCheckbox(employeeId) {
const index = this.selectedEmployees.indexOf(employeeId);
if(index === -1){
this.selectedEmployees = [...this.selectedEmployees, employeeId];
}else {
const newSelectedEmployees = [...this.selectedEmployees];
newSelectedEmployees.splice(index, 1);
this.selectedEmployees = newSelectedEmployees;
}
}
@action
toggleAddEmployee(){
this.addMode = !this.addMode;
}
}
export default EmployeeUiStore;
The weird thing is if I add something like this to my code 奇怪的是,如果我在代码中添加这样的内容
console.log(employeeUiStore.selectedEmployees.indexOf(0) >= 0)
Then states will update properly but when I remove this line then nothing is updated. 然后状态将正确更新,但是当我删除此行时,则没有任何更新。
I see that my toggleCheckbox is being triggered and the state is being updated. 我看到我的toggleCheckbox被触发并且状态正在更新。
I also do have @observer on this component. 我在此组件上也有@observer。
You are not dereferencing anything when you pass the data
array to the ReactTable
component. 当您将
data
数组传递给ReactTable
组件时,您不会取消引用任何东西。
You can resolve this by either using slice
or peek
on the array before you pass it to external libraries: 您可以通过在数组上使用
slice
或peek
来解决此问题,然后再将其传递给外部库:
<ReactTable
data={data.slice()}
columns={columns}
showPageSizeOptions={false}
resizable={false}
className="-striped -highlight"
defaultPageSize={12}
filterable={true}
/>
There is also no need for immutability in MobX. MobX中也不需要不变性。 You can alter the array straight away:
您可以立即更改数组:
class EmployeeUiStore {
@observable addMode = false;
@observable selectedEmployees = [];
@action
toggleCheckbox(employeeId) {
const index = this.selectedEmployees.indexOf(employeeId);
if (index === -1) {
this.selectedEmployees.push(employeeId);
} else {
this.selectedEmployees.splice(index, 1);
}
}
@action
toggleAddEmployee(){
this.addMode = !this.addMode;
}
}
export default EmployeeUiStore;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.