React功能组件在循环调用api时只返回api上传递的最后一个元素的响应。

问题描述 投票:0回答:1

母体部分

  data.map(eachData => (
     <ChildComponent
     key={eachData.id}
     child={eachData}
     />
  ))

儿童组件

props.getChildData({id: id}); 代码调用Redux动作并将其存储在reducer中。

function ChildComponent(props) {
const [id, setId] = React.useState(props.eachData.id)
useEffect(() => {
    let handler
    (function () {
      handler = setTimeout(() => {   
        props.getChildData({id: id})
      }, 1000)
    })();
    return () => {
      clearTimeout(handler)
    }
  }, [id])

}

Api调用正在发生,并在网络选项卡中进行验证。Redux商店只返回api响应的最后一个api响应。

javascript reactjs react-redux closures
1个回答
0
投票

你不正确地访问子组件中的id.id是在props.child里面,而不是在props.eachData里面,所以把useState改成像这样访问id。

const [id, setId] = React.useState(props.child.id);

这样就能正常工作了

© www.soinside.com 2019 - 2024. All rights reserved.