简体   繁体   English

React.js - 子组件道具未定义

[英]React.js - child component props undefined

I'm trying to pass data from parent to child component.我正在尝试将数据从父组件传递到子组件。 The data is fetched from API.数据取自 API。

Following is the parent component:以下是父组件:

const App = () => {

  const [item, setItem] = useState([]);

  useEffect(() => {

      const fetchData = async () => {
        const response = await fetch('http://jsonplaceholder.typicode.com/photos');
        const data = await response.json();
        setItem(data);
    }

      fetchData();

  }, [])

  const slidedData = item.slice(0, 10);

  const data = slidedData.reduce((acc, item) => {
    acc[item.title] = (acc[item.title] || 0) + 1;
    return acc;
  }, {});

    return (
          <Switch>
            <Route
              path="/child"
              render={() =>
                <Child data={data} />
              }
            />
          </Switch>
  )
}

export default App;

And the following is the child component which receives props:以下是接收道具的子组件:

const Child = ({ data }) => {

    const test = data.map(el => el);
    console.log(test);

}

Above code doesn't work.上面的代码不起作用。 It says 'TypeError: data.map is not a function'它说“TypeError:data.map 不是函数”

I understand this is because at the initial render the data is not ready for child component thus 'data' is undefined.我理解这是因为在初始渲染时,数据还没有为子组件准备好,因此“数据”是未定义的。 What should I do to make this 'data' work?我应该怎么做才能使这些“数据”发挥作用?

The typeOf data in Child component is not an Array, its an object and .map is an array function, hence the error. Child组件中的 typeOf data不是数组,它是object.maparray function,因此出现错误。 Check and log variable data instead.改为检查并记录变量data

One of the ways to iterate an object is below迭代 object 的方法之一如下

Object.keys(data).map(function(keyName, keyIndex) {
  ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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