簡體   English   中英

React MobX 不會在道具更改時觸發重新渲染

[英]React MobX not triggering rerender on props change

我是 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 檢查器時,我可以看到道具正在更新。

對我哪里出錯的任何建議?

您不會從組件的 render 方法中提供給map的函數返回任何內容。 添加return關鍵字,它將按預期工作。

{accounts.map((item, index) => {
  return <p key={index}>{item.name}</p>;
})}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM