【发布时间】:2020-09-25 00:31:42
【问题描述】:
我想做什么
- 子组件第一次渲染时,我想使用父组件的props中的值
问题
- 子组件第一次渲染时,子组件中没有设置props状态
我是React 的初学者。我正在尝试使用props 在子组件中的componentDidMount 中通过axios 调用API。我的意思是,我正在做的是在父组件中调用 API,并将此 API 中的数据设置为子组件为props。
但是,当我尝试这样做时,props 未在子组件中设置为 state。
例如,当我检索包含category 的产品时,我输入localhost:3000/api/parent/?category=1/。但是,我的console.log 向我展示了localhost:3000/api/parent/?category=undefined,因为我猜想在子组件第一次渲染时没有设置 props。
实际上,我可以在state 中看到category 对象,如下所示。
我猜props 完全设置为state 在子组件完成第一次渲染之后。
如何将来自 API 的 props 设置为 state?
虽然我尝试了很多在stackoverflow上找到的解决方案,但我被这个问题卡住了这么长时间。
我想让你告诉我一些解决方案。
非常感谢。
== == ==
我的代码是这样的。
父组件
class Top extends Component {
constructor(props) {
super(props);
this.state = {
loginUser: '',
categories: [],
};
}
async componentDidMount() {
const localhostUrl = 'http://localhost:8000/api/';
const topCategoryList = ['Smartphone', 'Tablet', 'Laptop'];
let passCategoryToState=[]
axios
.get(localhostUrl + 'user/' + localStorage.getItem('uid'))
.then((res) => {
this.setState({ loginUser: res.data });
})
.catch((err) => console.log(err));
await Promise.all(
topCategoryList.map(async (category) => {
await axios.get(localhostUrl + 'category/?name=' + category).then((res) => {
passCategoryToState=[...passCategoryToState, res.data]
console.log(passCategoryToState);
});
})
);
this.setState({categories : passCategoryToState})
}
render() {
if (!this.props.isAuthenticated) {
return <p> Developing now </p>;
}
if (this.state.loginUser === '' ) {
return <CircularProgress />;
} else {
return (
<>
<Header loginUser={this.state.loginUser} />
<Give_Item_List
axiosUrl="http://localhost:8000/api/"
subtitle="Smartphone Items"
loginUser={this.state.loginUser}
category={this.state.categories[0]}
/>
</>
);
}
}
}
export default Top;
还有,子组件
class Give_Item_List extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
loginUser: this.props.loginUser,
category: this.props.category,
};
}
async componentDidMount() {
let pickedGiveItems;
await this.setState({ loading: true });
await axios
.get(this.props.axiosUrl + 'giveitem/?category=' + this.state.category.id)
.then((res) => {
pickedGiveItems = res.data;
console.log(pickedGiveItems);
})
.catch((err) => console.log('Not found related to Items'));
this.setState({ loading: false });
}
render() {
if (this.state.loading == true) {
return <CircularProgress />;
}
return <h1>Give_Item_List</h1>;
}
}
export default Give_Item_List;
==============
编辑:更改为componentDidUpdate
componentDidUpdate(prevProps) {
if(prevProps.category != this.props.category){
let pickedGiveItems;
this.setState({ loading: true });
axios
.get(this.props.axiosUrl + 'giveitem/?category=' + this.props.category.id)
.then((res) => {
pickedGiveItems = res.data;
console.log(pickedGiveItems);
})
.catch((err) => console.log('NotFount'));
this.setState({ loading: false });
}
}
还是不行……
【问题讨论】:
标签: reactjs asynchronous react-props setstate