如何将reducer的返回值设置为react js组件中的状态对象 [英] how can I set the reducer's return value to state object in component in react js

查看:38
本文介绍了如何将reducer的返回值设置为react js组件中的状态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件如下.我在其 componentDidMount() 事件上调用 api.我不明白为什么在组件渲染时我没有第一次获得它的 prop 值.我也不确定为什么组件渲染了 2 次.我有以下代码.

import React, { Component } from "react";从react-redux"导入{连接};从react-router-dom"导入{链接};从./AgmtTable"导入 AgmtTable;import * as AgmtAction from "../redux/actions/AgmtAction";类 AgmtContainer 扩展组件 {构造函数(道具){超级(道具);this.state = {};}获取 Agmt 详细信息.componentDidMount() {this.props.dispatch(AgmtAction.getAgmtsForCustomer(this.props.match.params.custID,this.props.match.params.source,this.props.token));console.log("componentDidMount", this.props.Agmts);}getHeaader = () =>{var tableHeadings = ["Agmt ID",开始日期",结束日期",];返回 tableHeadings.map((key) => {return {key.toUpperCase()}</th>;});};getRowsData = () =>{console.log("in row data", this.props.Agmts);//这里我看不到数据,尽管它存在于 mapStateToProps() 函数中.我收到错误,因为 this.props.agreements.map 不是函数.如果(this.props.Agmts){返回 this.props.Agmts.map((value) => {常量{Agmt_ID,Agmt_START_DATE,结束日期,} = 值;返回 (<tr key={Agmt_ID} className="clickable-row active"><td>{Agmt_ID} </td><td>{Agmt_START_DATE} </td><td>{End_DATE} </td></tr>);});}};使成为() {返回 (<React.Fragment><div><表id="显示表"className="table table-bordered table-hover table-responsive table-condensed table-striped table-sm"><tr>{this.getHeaader()}</tr>{this.getRowsData()}</tbody>

</React.Fragment>);}}函数 mapStateToProps(state) {返回 {Agmts: state.AgmtsDetails.AgmtsData,//这里有数据令牌:state.login.userDetails.token,};}导出默认连接(mapStateToProps)(AgmtContainer);

还有我如何使用 mapStateToProps 值来设置状态对象.当我运行上面的代码时,我收到错误,因为 this.props.agmts.map 不是函数

解决方案

分派是异步的,因此您需要使用 componentDidUpdate 或在 Redux 商店中观察要更新的结果 直接从reducer返回结果.

获得结果后,您可以对其进行操作并将其存储在本地状态中以在渲染中引用.注意,除非你需要在其他组件的某处引用结果,否则你不需要将它存储在 Redux 中,你可以在组件内处理它.

使用 componentDidUpdate 订阅商店:

componentDidMount() {this.props.dispatch(AgmtAction.getAgmtsForCustomer(this.props.match.params.custID,this.props.match.params.source,this.props.token));}componentDidUpdate(prevProps) {if (JSON.stringify(prevProps.Agmts) !== JSON.stringify(this.props.Agmts)) {//这是调度的结果控制台日志(this.props.Agmts);}}

直接返回结果:

//在您的 AgmtAction.getAgmtsForCustomer 操作中export const getAgmtsForCustomer = () =>(调度,getState) =>{返回 axios.得到(...........then((res) => {派遣(..........返回 res.data;}).catch((错误) => {...});};//在你的 `AgmtContainer` 组件中...componentDidMount() {this.props.dispatch(AgmtAction.getAgmtsForCustomer(this.props.match.params.custID,this.props.match.params.source,this.props.token)).then((res) => {//这是调度的结果控制台日志(res);});}

I have one component as below. I am calling on api on its componentDidMount() event. I am not getting why am I not getting its prop value first time when component renders. Also I am not sure why component is rendering 2 times. I have below code.

import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import AgmtTable from "./AgmtTable";
import * as AgmtAction from "../redux/actions/AgmtAction";

class AgmtContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  fetch Agmt details.
  componentDidMount() {
    this.props.dispatch(
      AgmtAction.getAgmtsForCustomer(
        this.props.match.params.custID,
        this.props.match.params.source,
        this.props.token
      )
    );
    console.log("componentDidMount", this.props.Agmts);
  }

  getHeaader = () => {
    var tableHeadings = [
      "Agmt ID",
      "Start Date",
      "End Date",
    ];
    return tableHeadings.map((key) => {
      return <th key={key}> {key.toUpperCase()}</th>;
    });
  };

  getRowsData = () => {
    console.log("in row data", this.props.Agmts);//here I cant see a data though its present in mapStateToProps() function. I am getting error as this.props.agreements.map is not a function.
     if (this.props.Agmts) {
       return this.props.Agmts.map((value) => {
         const {
           Agmt_ID,
           Agmt_START_DATE,
           End_DATE,

         } = value;
         return (
           <tr key={Agmt_ID} className="clickable-row active">
             <td> {Agmt_ID} </td>
             <td> {Agmt_START_DATE} </td>
             <td> {End_DATE} </td>
             </tr>
         );
       });
     }
  };

  render() {
    return (
      <React.Fragment>
        <div>
          <table
            id="display-table"
            className="table table-bordered table-hover table-responsive table-condensed table-striped table-sm"
          >
            <tbody>
              <tr>{this.getHeaader()}</tr>
              {this.getRowsData()}
            </tbody>
          </table>
        </div>
      </React.Fragment>
    );
  }
}

function mapStateToProps(state) {
  return {
    Agmts: state.AgmtsDetails.AgmtsData,//here I have a data
    token: state.login.userDetails.token,
  };
}

export default connect(mapStateToProps)(AgmtContainer);

Also how can I use the mapStateToProps values to set in state object. When I am running above code I am getting error as this.props.agmts.map is not a function

解决方案

The dispatch is asynchronous, so you either need to watch for result to be updated in your Redux store with componentDidUpdate or directly return the result from the reducer.

When you get the result, you can manipulate it and store it in local state to reference in your render. Note that unless you need to reference the result in another component somewhere, then you don't need to store it in Redux, you can handle it all in within the component.

Subscribing to the store with componentDidUpdate:

componentDidMount() {
  this.props.dispatch(
    AgmtAction.getAgmtsForCustomer(
      this.props.match.params.custID,
      this.props.match.params.source,
      this.props.token
    )
  );
}

componentDidUpdate(prevProps) {
  if (JSON.stringify(prevProps.Agmts) !== JSON.stringify(this.props.Agmts)) {
    // this is the result of the dispatch
    console.log(this.props.Agmts);
  }
}

Returning the result directly back:

// in your AgmtAction.getAgmtsForCustomer action
export const getAgmtsForCustomer = () => (dispatch, getState) => {
  return axios
    .get(..........
    .then((res) => {
      dispatch(..........
        return res.data;
      })
    .catch((err) => {
      ...
    });
};

// in your `AgmtContainer` component
...
componentDidMount() {
  this.props.dispatch(
    AgmtAction.getAgmtsForCustomer(
      this.props.match.params.custID,
      this.props.match.params.source,
      this.props.token
    )
  ).then((res) => {
    // this is the result of the dispatch
    console.log(res);
  });
}

这篇关于如何将reducer的返回值设置为react js组件中的状态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆