React Redux从表中的reducer读取数据

时间:2019-08-17 17:47:48

标签: reactjs redux

我对react-redux还是很陌生,我试图读取表中的硬编码初始数据,但是我尝试了很多,但是我未能实现这一目标。现在,我对这个最简单的事情感到非常疲惫。

这是我的postreducer.js文件

const initialState = [{name: 'jhon', age: '23', email: 'a@a'}, {name: 'doe', age: '24', email: 'b@a'}];

const postReducer = (state = initialState, action) => {
    switch(action.type) {
      case 'ADD_POST':
        return null
      default:
        return state;
    }
  }
  export default postReducer;

您可能会注意到,处于初始状态,我正在尝试在表格中显示这些状态。

import React, {Fragment} from "react"
import { connect } from 'react-redux'


class Table extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            employees: this.props.employees
        };

    }


    render() {
        return (
            <Fragment>
                <thead>
                    <tr>
                        <th scope="col">Name</th>
                        <th scope="col">Age</th>
                        <th scope="col">Email</th>
                    </tr>
                </thead>
                <tbody>
                {this.props.employees.map((item, index) => (
                    <tr key={index}>
                        <td>{item.name}</td>
                        <td>{item.age}</td>
                        <td>{item.email}</td>
                    </tr>
                ))}
                </tbody>
            </Fragment>
        );
    }
}

function mapStateToProps(state) {
    const { employees } = state
    return { employees: employees }
  }

  export default connect(mapStateToProps)(Table)

这是我的App.js文件:

import React from "react"
import Table from "./table"

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
        };
    }


    render() {
        return (
            <React.Fragment>              
            <table>
                <Table />
            </table>
            </React.Fragment>
        );
    }
}
export default App;

这是我的index.js文件:

import React from "react";
import ReactDOM from "react-dom";

import App from "./components/App";

import { Provider } from 'react-redux'

import { createStore } from 'redux'
import postReducer from '../src/redux/reducers/postReducer'

const store = createStore(postReducer)


ReactDOM.render((
  <Provider store={store}>
      <App />
  </Provider>
), document.getElementById('app'))

有人可以帮我在带有Redux的表中显示initialstate数据吗?

1 个答案:

答案 0 :(得分:0)

function mapStateToProps(state) {
    const { employees } = state
    return { employees: employees }
  }

您正在从州拉回employees,但是您的initial state中没有雇员变量。这是您的第一个错误。因此,请更改您的initial state

const initialState = {
      employees: [{name: 'jhon', age: '23', email: 'a@a'}, {name: 'doe', age: '24', email: 'b@a'}] 
};

 constructor(props) {
        super(props);
        this.state = {
            employees: this.props.employees
        };
    }

为什么要将props设置为state。不要这样做。使用this.props.employees访问数据。