为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 `componentDidMount ` 获取状态(使用 Redux)?

如何从 `componentDidMount ` 获取状态(使用 Redux)?

心有法竹 2023-04-27 10:25:21
我对 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 });

        }

    }


查看完整回答
反对 回复 2023-04-27
  • 1 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信