简体   繁体   English

React MobX 不会在道具更改时触发重新渲染

[英]React MobX not triggering rerender on props change

I'm new to MobX and I am having some issues calling async actions.我是 MobX 的新手,我在调用异步操作时遇到了一些问题。 My store has a async function for updating an observabel array:我的商店有一个用于更新 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;
        })
    }
}

}

But my component does not rerender on update (which is called on componentDidMount):但是我的组件不会在更新时重新渲染(在 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;

I can see the props are getting updated when i use the React inspector in Chrome.当我在 Chrome 中使用 React 检查器时,我可以看到道具正在更新。

Any suggestions to where I am going wrong?对我哪里出错的任何建议?

You are not returning anything from the the function given to map in the render method of your component.您不会从组件的 render 方法中提供给map的函数返回任何内容。 Add the return keyword and it will work as expected.添加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