反应-mapStateToProps-“状态未定义”

时间:2020-01-05 20:27:45

标签: javascript reactjs redux

我遇到以下问题:使用下面的代码,我得到了错误:

this.props.posts未定义

当我按照教程https://codeburst.io/redux-a-crud-example-abb834d763c9进行操作时,我输入的所有内容都正确无误,在我进入React生涯之初,我已经完全感到困惑。你能帮我吗?

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Post from './Post';

class AllPost extends Component {
    render() {
        return (
            <div>
                <h1>All Posts</h1>
                {this.props.posts.map((post) => <Post key={post.id} post={post} />)}
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        posts: state,
    }
}

export default connect(mapStateToProps)(AllPost);

2 个答案:

答案 0 :(得分:0)

非常感谢您的努力!

以下是postReducer:

const postReducer = (state = [], action) => {
    switch(action.type) {
        case 'ADD_POST':
            return state.concat([action.data]);
        default:
            return state;
    }
}

export default postReducer;

这里是index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import { createStore } from 'redux';
import { Provider } from 'react-redux';
import postReducer from './reducers/postReducer';

const store = createStore(postReducer);

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

答案 1 :(得分:0)

您需要声明一个初始状态。因此您的this.props.posts不会是undefined

const initialState = {
  posts: []
}

const postReducer = (state = initialState, action) => {
    switch(action.type) {
        case 'ADD_POST':
            return { ...state, posts: [...state.posts, action.data]}
        default:
            return state;
    }
}

export default postReducer;

第二个错误位于您的mapStateToProps方法内部。您需要访问posts还原状态密钥。 posts: state.posts就像我在下面所做的

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Post from './Post';

class AllPost extends Component {
    render() {
        return (
            <div>
                <h1>All Posts</h1>
                {this.props.posts.map((post) => <Post key={post.id} post={post} />)}
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        posts: state.posts, // you need to access to posts key
    }
}

export default connect(mapStateToProps)(AllPost);