【问题标题】:Fetching data from server through Redux (Action & Reducer) fails to store the data in the State通过 Redux (Action & Reducer) 从服务器获取数据无法将数据存储在 State
【发布时间】:2019-12-15 12:45:41
【问题描述】:

我正在尝试通过 Redux(使用操作和缩减程序)获取数据并将其存储在 ReactTable 中

这是表格:

// MisleadLeadsTable
import React from "react";
import "react-table-v6/react-table.css";
import ReactTable from "react-table-v6";
import { connect } from "react-redux";
import {
  getLeadsNotValid,
  updateSpecificNotValidLead
} from "../../actions/leads";
import Spinner from "../layout/Spinner";

class MisleadLeadsTable extends React.Component {
  constructor(props) {
    super();
    const { getLeadsNotValid } = props;
    // Going to get data from the Server
    // Call the Action and use the Reducer
    getLeadsNotValid();

    // Later put the data in the state
    this.state = {
      data: []
    };
    this.renderEditable = this.renderEditable.bind(this);
  }

  componentDidMount() {
    // TODO 
    const { leadsNotValid } = this.props;
    this.setState({
      data: leadsNotValid
    });
  }

  // Edit the cells
  renderEditable(cellInfo) {
    return (
      <div
        style={{ backgroundColor: "#fafafa" }}
        contentEditable
        suppressContentEditableWarning
        onBlur={e => {
          const data = [...this.state.data];
          data[cellInfo.index][cellInfo.column.id] = e.target.innerHTML;
          this.setState({ data });
        }}
        dangerouslySetInnerHTML={{
          __html: this.state.data[cellInfo.index][cellInfo.column.id]
        }}
      />
    );
  }

  render() {
    // loading data or not
    const { loadingData } = this.props;

    // This "data" should hold the fetched data from the server
    const { data } = this.state;
    return (
      <div>
        {loadingData ? (
          <Spinner />
        ) : (
          <div>
            <ReactTable
              data={data}
              columns={[
                {
                  Header: "Business Name",
                  accessor: "BusinessName"
                  // Cell: this.renderEditable
                }
              ]}
              defaultPageSize={10}
              className="-striped -highlight"
            />
            <br />
          </div>
        )}
      </div>
    );
  }
}

const mapStateToProps = state => ({
  loadingData: state.leadReducer.loadingData,
  leadsNotValid: state.leadReducer.leadsNotValid
});

const mapDispatchToProps = { getLeadsNotValid, updateSpecificNotValidLead };

export default connect(mapStateToProps, mapDispatchToProps)(MisleadLeadsTable);

但是,当我尝试将数据存储在 State 中(在 componentDidMount 中)时,它总是返回 empty ,并且在呈现表时它得到一个空数组。

将数据存储在 State 中至关重要,因为我正在尝试实现一个可编辑的表。

数据存储在leadsNotValid,如果我这样做:

<ReactTable
  data={leadsNotValid}          // Notice !! Changed this
  columns={[
    {
      Header: "Business Name",
      accessor: "BusinessName"
      // Cell: this.renderEditable
    }
  ]}
  defaultPageSize={10}
  className="-striped -highlight"
/>

然后数据成功呈现给用户,但是它不在组件的状态中。

如何使用setStateleadsNotValid 放入状态?

如果需要,这里是 Action & Reducer(它们工作得很好!):

行动:

import axios from "axios";
import {
  REQUEST_LEADS_NOT_VALID,
  REQUEST_LEADS_NOT_VALID_SUCCESS,
  UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID,
  UPDATE_A_SINGLE_NOT_VALID_LEAD
} from "./types";

export const updateSpecificNotValidLead = updatedLead => async dispatch => {
  dispatch({
    type: UPDATE_A_SINGLE_NOT_VALID_LEAD
  });

  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };
  const body = JSON.stringify({ updatedLead });

  const res = await axios.post(
    ".......API/Something1/....",
    body,
    config
  );

  if (res !== null && res.data !== null) {
    dispatch({
      type: UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID
    });
  }
};


export const getLeadsNotValid = () => async dispatch => {
  dispatch({
    type: REQUEST_LEADS_NOT_VALID
  });

  const res = await axios.get(".......API/Something2/....");
  if (res !== null && res.data !== null) {
    dispatch({
      type: REQUEST_LEADS_NOT_VALID_SUCCESS,
      payload: res.data
    });
  }
};

减速机:

import {
  GET_MAIN_LEADS_SUCCESS,
  REQUEST_MAIN_LEADS,
  RELOAD_DATA_MAIN_LEADS_TABLE,
  REQUEST_LEADS_NOT_VALID,
  REQUEST_LEADS_NOT_VALID_SUCCESS,
  UPDATE_A_SINGLE_NOT_VALID_LEAD,
  UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID
} from "../actions/types";

const initialState = {
  mainLeadsClients: [],
  loadingData: null, // general loader
  reloadMainLeadTable: 0,
  reloadMisleadTable: 0,
  leadsNotValid: []
};

export default function(state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case REQUEST_LEADS_NOT_VALID:
      return {
        ...state,
        loadingData: true
      };

    case REQUEST_LEADS_NOT_VALID_SUCCESS:
      return {
        ...state,
        loadingData: false,
        leadsNotValid: payload
      };
    case UPDATE_A_SINGLE_NOT_VALID_LEAD:
      return {
        ...state,
        loadingData: true
      };
    case UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID:
      return {
        ...state,
        reloadMisleadTable: state.reloadMisleadTable + 1,
        loadingData: false
      };


    // ... more 

    default:
      return state;
  }
}

【问题讨论】:

    标签: javascript reactjs redux reducers


    【解决方案1】:

    您可能必须编写 super(props) 而不是 super() 才能访问构造函数中的 props。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 2022-12-11
      • 2016-08-03
      相关资源
      最近更新 更多