【问题标题】:React MobX not triggering rerender on props changeReact MobX 不会在道具更改时触发重新渲染
【发布时间】:2019-04-01 12:12:37
【问题描述】:

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

对我哪里出错有什么建议吗?

【问题讨论】:

  • 组件不会在 props 更改时重新渲染,除非你用 shouldComponentUpdategetDerivedStateFromProps 之类的东西告诉它。
  • 您是否订阅了这些更改?
  • 我的印象是@observer 会跟踪更新?我将如何订阅?
  • 只是对@Tholle 答案的补充,如果map 中没有逻辑并且只想返回一个标签,您可以使用( 而不是{,就像{accounts.map((item, index) =&gt; (&lt;p key={index}&gt;{item.name}&lt;/p&gt;) )} 这样像return

标签: reactjs typescript mobx mobx-react


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2019-09-22
    • 2014-08-22
    相关资源
    最近更新 更多