You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用easy-peasy如何在组件初始化时读取并渲染store中的列表数据

问题原因

你的代码核心问题出在getInitialChurches thunk的异步逻辑处理上:
data.map(async () => {})会返回一个Promise数组,你没有等待这些异步请求完成就调用了actions.setAllChurches(array),此时传入的是空数组。后续请求完成后你直接往array里push数据的操作是修改已存入store的数组引用,没有走easy-peasy的action更新逻辑,框架感知不到状态变化,自然不会触发组件重渲染。

修复方案

修改churchModel中的getInitialChurches逻辑,等待所有详情接口请求完成、拿到完整的教堂列表后,再统一更新store状态:

const churchModel = {
  items: [],

  // ACTIONS
  setAllChurches: action((state, payload) => {
    state.items = payload;
  }),
  getInitialChurches: thunk(async (actions) => {
    const { data: geoList } = await axios.post(
      'http://localhost:3000/api/geo/closeto?latlong=2.3522219 48.856614&distance=10000'
    );
    // 等待所有详情请求执行完毕,拿到完整列表
    const churchList = await Promise.all(
      geoList.map(async (item) => {
        const res = await axios.get(`http://localhost:3000/api/institutions/all?idInstitution=${item.idInstitution}`);
        return res.data[0];
      })
    );
    // 统一更新store状态,触发组件重渲染
    actions.setAllChurches(churchList);
  })
}

可选优化

你可以在组件中加空状态判断,避免空数组时页面空白:

return (
  <div className={classes.root} style={{marginTop: '20px',}}>
    {churches.length === 0 ? (
      <p>加载中...</p>
    ) : (
      churches.map( (church) => (
        <ChurchItem 
          key={ church.idInstitution } 
          church={ church }
          setActiveItem={setActiveItem}
          activeItem={activeItem}
        />
      ))
    )}
  </div>
)

内容的提问来源于stack exchange,提问作者nicolas moreau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:45:02