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

我对 React 和 Redux 很陌生,所以问题可能很明显。


我尝试使用 fetch API 从我的服务器通过用户 ID获取一些信息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);

但是当我尝试从中获取当前用户的状态时,componentDidMount()它是null。在渲染中,它实际上显示了状态。


我应该怎么做才能从服务器获取状态componentDidMount()并成功从服务器获取信息?


心有法竹
浏览 105回答 1
1回答

慕少森

我找到了答案。我应该用componentDidUpdate()而不是componentDidMount()并且还需要检查状态以避免无限循环。所以最后componentDidUpdate()应该是这样的:&nbsp; &nbsp; async componentDidUpdate() {&nbsp; &nbsp; &nbsp; &nbsp; const response = await fetch(`http://192.168.0.16:5000/api/drinks/users/${this.props.currentUser.id}`);&nbsp; &nbsp; &nbsp; &nbsp; const json = await response.json();&nbsp; &nbsp; &nbsp; &nbsp; if (this.state.DCs.length === 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; await this.setState({ DCs: json.drinkCons });&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript