gpt4 book ai didi

javascript - React+mobx 不在初始页面加载时呈现

转载 作者:行者123 更新时间:2023-11-30 18:59:38 25 4
gpt4 key购买 nike

我尝试深入研究 React+mobx,但遇到了问题。我有从服务器获取数据的商店,并且在获取结束后必须在页面上表示获取的数据。错误出现在初始加载时 - 获取后没有数据呈现(获取的数据已加载,显示在控制台的网络选项卡中)。但是,如果我尝试从菜单再次转到此页面 - 数据会呈现在页面上。

为了理解一个问题,我准备了带有获取虚拟数据的 gitHub 存储库

Test repo

要重现错误,只需clone repo。以及 npm inpm start

提前致谢

最佳答案

我发现了问题(并从中吸取了教训 :))。

你的商店应该是这样的

export class DashboardStore extends BaseStore {

@observable stat = []; // <-- your response is an array, so start with array

@observable regInfo = [];
@observable regInfoReady = false;

fetchStat = async () => {
const statResponse = await this.callApi('fetchStat');
runInAction(() => { //async methods can't be marked as action, cause they are async
this.stat = statResponse;
});
};
}

令我惊讶的是,如果 render 方法被定义为带箭头功能的属性,将不会在可观察到的变化时重新渲染。

所以只需将 render 更改为类的方法即可。

// Dashboard/index.jsx

...
render() {
const { stat, regInfo, regInfoReady } = this.props.dashboardStore;

return (
<div>
<Row gutter={16} style={{ padding: '30px 0px 30px 0px' }}>
<Col span={8}>
<Card title="Titles" bordered={false}>
{stat.length && stat.map(row => (
<div key={row.id}>
{row.title}
</div>
))}
</Card>
</Col>
</Row>
</div>
);
}
...

关于javascript - React+mobx 不在初始页面加载时呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59648195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com