Reactjs React MobX在道具更换时不触发重新启动
我是MobX新手,在调用异步操作时遇到了一些问题。My store具有用于更新observabel阵列的异步函数:Reactjs React MobX在道具更换时不触发重新启动,reactjs,typescript,mobx,mobx-react,Reactjs,Typescript,Mobx,Mobx React,我是MobX新手,在调用异步操作时遇到了一些问题。My store具有用于更新observabel阵列的异步函数: export class AccountStore implements IAccountStore { @observable accounts:any = []; @observable state = "pending"; // "pending" / "done" / "error" @action public async getAccounts() { thi
export class AccountStore implements IAccountStore {
@observable accounts:any = [];
@observable state = "pending"; // "pending" / "done" / "error"
@action
public async getAccounts() {
this.state = "pending"
try {
const res = await accountsService.getAll();
runInAction(() => {
console.log(res);
this.state = "done";
this.accounts.replace(res.data);
})
} catch (error) {
runInAction(() => {
this.state = error;
})
}
}
}
但我的组件不会在更新时重新提交(在componentDidMount上调用):
接口AppProps{
accountStore:IAccountStore
}
@注入('accountStore')
@观察者
类扩展组件{
构造器(道具:任何){
超级(道具);
}
公共组件didmount(){
this.props.accountStore.getAccounts();
console.log(this.props.accountStore)
}
render(){
const accounts=this.props.accountStore.accounts;
返回(
所有账户
{accounts.map((项目:任意,索引:编号)=>{
{item.name}
})
}
this.props.accountStore.getAccounts()}>Update
);
}
}
输出默认计数;
当我在Chrome中使用React inspector时,我可以看到道具正在更新
对我的错误有什么建议吗?在组件的渲染方法中,您没有从给定给
map
的函数返回任何内容。添加return
关键字,它将按预期工作
{accounts.map((item, index) => {
return <p key={index}>{item.name}</p>;
})}
{accounts.map((项目,索引)=>{
返回{item.name}
;
})}
组件不会在道具更改时重新渲染,除非您告诉它使用类似于shouldComponentUpdate
或getDerivedStateFromProps
的内容。您是否订阅更改?我的印象是@observer
会跟踪更新?我该怎么订阅呢?这只是@Tholle答案的一个补充,如果map
中没有逻辑,只想返回一个标记,你可以使用(
而不是{
像{accounts.map((item,index)=>({item.name}
)}
,所以它的工作原理类似于return code>
{accounts.map((item, index) => {
return <p key={index}>{item.name}</p>;
})}