React+mobx 不在初始页面加载时呈现
React+mobx not render on initial page loading
我尝试深入研究 React+mobx 但遇到了问题。我有从服务器获取数据的商店,并且在获取结束后必须在页面上表示获取的数据。错误出现在初始加载时 - 获取后没有数据呈现(获取的数据已加载,显示在控制台的网络选项卡中)。
但是,如果我尝试从菜单再次转到此页面 - 数据会呈现在页面上。
为了理解一个问题,我准备了 gitHub 回购以获取虚拟数据
为了重现错误,只需 clone
回购。并且 npm i
和 npm 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
方法被定义为带有箭头函数的 属性, 将不会在 observable 上重新渲染改变。
所以只需将 render
更改为 class 的方法即可。
// 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>
);
}
...
我尝试深入研究 React+mobx 但遇到了问题。我有从服务器获取数据的商店,并且在获取结束后必须在页面上表示获取的数据。错误出现在初始加载时 - 获取后没有数据呈现(获取的数据已加载,显示在控制台的网络选项卡中)。 但是,如果我尝试从菜单再次转到此页面 - 数据会呈现在页面上。
为了理解一个问题,我准备了 gitHub 回购以获取虚拟数据
为了重现错误,只需 clone
回购。并且 npm i
和 npm 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
方法被定义为带有箭头函数的 属性, 将不会在 observable 上重新渲染改变。
所以只需将 render
更改为 class 的方法即可。
// 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>
);
}
...