React MobX不会触发对道具更改的重新渲染

问题描述 投票:1回答:1

我是MobX的新手,我遇到了一些调用异步操作的问题。我的商店有一个用于更新observabel数组的异步函数:

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上调用):

interface AppProps {
accountStore: IAccountStore
}

@inject('accountStore')
@observer
class AllAcounts extends Component<AppProps, any> {
constructor(props: any) {
    super(props);
}

public componentDidMount() {
    this.props.accountStore.getAccounts();
    console.log(this.props.accountStore)
}

render() {
    const accounts = this.props.accountStore.accounts;
    return (
        <div>
            <h4>All accounts</h4>
            {accounts.map((item: any, index: number) => {
                <p key={index}>{item.name}</p>
            })
            }
            <button onClick={() => this.props.accountStore.getAccounts()}>Update</button>
        </div>
    );
}
}

export default AllAcounts;

当我在Chrome中使用React检查器时,我可以看到道具正在更新。

对我出错的地方有什么建议吗?

reactjs typescript mobx mobx-react
1个回答
1
投票

您没有从组件的render方法中给map的函数返回任何内容。添加return关键字,它将按预期工作。

{accounts.map((item, index) => {
  return <p key={index}>{item.name}</p>;
})}
© www.soinside.com 2019 - 2024. All rights reserved.