Javascript 如何从“componentDidMount”(使用Redux)获取状态?
我对反应和重复是个新手,所以问题很明显 我试图通过用户id在Javascript 如何从“componentDidMount”(使用Redux)获取状态?,javascript,reactjs,redux,Javascript,Reactjs,Redux,我对反应和重复是个新手,所以问题很明显 我试图通过用户id在componentDidMount 我对DC的本地状态没有问题-我需要从Redux获取用户id import React from 'react'; import {connect} from 'react-redux'; class DrinkPage extends React.Component { constructor() { super(); this.state = { DCs: [],
componentDidMount
我对DC的本地状态没有问题-我需要从Redux获取用户id
import React from 'react';
import {connect} from 'react-redux';
class DrinkPage extends React.Component {
constructor() {
super();
this.state = {
DCs: [],
};
}
async componentDidMount() {
const response = await fetch(
`http://localhost:5000/api/drinks/users/${this.props.currentUser.id}`,
);
console.log(this.props.currentUser.id);
const json = await response.json();
await this.setState({DCs: json.drinkCons});
}
render() {
const DC = this.state.DCs;
console.log(this.props.currentUser, 'render');
return (
<div className="App">
<CardList DCs={DC} />
</div>
);
}
}
const mapStateToProps = (state) => ({
currentUser: state.user.currentUser,
});
export default connect(mapStateToProps)(DrinkPage);
从“React”导入React;
从'react redux'导入{connect};
类DrinkPage扩展了React.Component{
构造函数(){
超级();
此.state={
跟单信用证:[],
};
}
异步组件didmount(){
const response=等待获取(
`http://localhost:5000/api/drinks/users/${this.props.currentUser.id}`,
);
console.log(this.props.currentUser.id);
const json=await response.json();
等待这个.setState({DCs:json.drinkCons});
}
render(){
const DC=this.state.DCs;
log(this.props.currentUser'render');
返回(
);
}
}
常量mapStateToProps=(状态)=>({
currentUser:state.user.currentUser,
});
导出默认连接(MapStateTops)(DrinkPage);
但是当我试图从componentDidMount()
获取当前用户的状态时,它是null
。
在render中,它实际显示状态
如何从componentDidMount()
获取状态并成功从服务器获取信息?我找到了答案
我应该使用componentdiddupdate()
而不是componentDidMount()
还需要检查状态以避免无限循环
所以最后,componentDidUpdate()
应该是这样的:
async componentDidUpdate() {
const response = await fetch(`http://192.168.0.16:5000/api/drinks/users/${this.props.currentUser.id}`);
const json = await response.json();
if (this.state.DCs.length === 0) {
await this.setState({ DCs: json.drinkCons });
}
}
你说的“得到国家”是什么意思?您是否尝试过
console.log(this.state.DCs)
?状态更改是异步的,但您不能等待它们(因为它们是由React批处理在一起的)。但是,您可以将函数作为第二个参数传递给this.setState
,它将在更改后运行。这是否回答了您的问题?如果未设置props.currentUser
,则可以尝试不安装组件。不确定在尚未设置用户时为什么要尝试获取当前用户的数据。