我在将从 API 获取的数据从子级传输到父级时遇到问题
child :
class Carton extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
matchData: []
};
}
这里我从 API 获取数据并更新状态
async componentDidMount() {
setTimeout(() => {
this.loading = true;
fetch(url)
.then(res => res.json())
.then(data => {
this.setState({
matchData: data.doc[0].data[this.props.sportId].realcategories
});
});
}, 500);
我已经从 API 循环了嵌套对象并将其显示在子对象中,但我不知道如何将嵌套对象的数据获取到父对象。这是一个示例,我需要深入多少才能获得所需的值
getData() {
this.state.matchData.map((data, i) =>
data.tournaments.map((tour, j) =>
tour.matches.map((matc, k) =>
//values of objects that i need to render a card in Child component
)//...
我的第一个问题是,练习从父级中的 API 获取数据然后将对象传递给子级是否更好?
如何将这些对象传递给父级,以便我可以迭代并选择其中的前 5 个 示例
如果有人有任何想法或建议,请告诉我
Br
史蒂夫
最佳答案
My first question is if it's better to practice to fetch data from API in parent and then pass objects to the child?
这要看情况。如果您的父对象需要了解子对象,而子对象内部没有发生任何事件(例如单击、焦点、模糊等),那么 API 调用应该发生在父对象内部。如果情况并非如此,并且父级只需要知道哪些子元素对子级起作用,那么您可以使用从父级传递到子级的函数。
例如:
class Parent {
const handleSelection = childData => {
doSomething(childData)
}
render() {
return(
<Child handleSelection={handleSelection} />
)
}
}
class Child {
render() {
const { myData } = this.state;
return(
<div onClick={() => this.props.handleSelection(myData)} />
)
}
}
当用户单击子组件中的 div 时,这会将数据从子组件传回父组件。希望这会有所帮助。
关于javascript - ReactJS - 循环遍历子对象并在父对象中显示前 10 个子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58904665/