我对 React 和 Redux 很陌生,所以问题可能很明显。我尝试使用 fetch API 从我的服务器通过用户 ID获取一些信息componentDidMount我对 DC 的本地状态没有问题——我需要从 Redux获取用户 IDimport 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);但是当我尝试从中获取当前用户的状态时,componentDidMount()它是null。在渲染中,它实际上显示了状态。我应该怎么做才能从服务器获取状态componentDidMount()并成功从服务器获取信息?
1 回答
慕少森
TA贡献2019条经验 获得超9个赞
我找到了答案。
我应该用componentDidUpdate()而不是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 });
}
}
添加回答
举报
0/150
提交
取消