简体   繁体   中英

React MobX not triggering rerender on props change

I'm new to MobX and I am having some issues calling async actions. My store has a async function for updating an observabel array:

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):

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.

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. Add the return keyword and it will work as expected.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM