首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过Redux (Action & Reducer)从服务器获取数据时,无法将数据存储在状态中

通过Redux (Action & Reducer)从服务器获取数据时,无法将数据存储在状态中
EN

Stack Overflow用户
提问于 2019-12-15 20:45:41
回答 1查看 195关注 0票数 0

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

下面是表格:

代码语言:javascript
复制
// 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);

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

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

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

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

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

如何使用setStateleadsNotValid置于状态?

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

操作:

代码语言:javascript
复制
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
    });
  }
};

减速机:

代码语言:javascript
复制
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;
  }
}
EN

回答 1

Stack Overflow用户

发布于 2019-12-16 15:56:22

为了在构造函数中访问props,您可能必须编写super(props)而不是super()。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59344026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档