为什么我无法访问子React组件中的Redux存储?

时间:2019-05-07 21:00:34

标签: reactjs react-redux

我试图了解如何将Redux状态映射到React组件。我不太确定这里出了什么问题,所以我只发布代码和收到的错误消息。

我的redux存储区:

const initialState = {
  userPosts: [{
    0: {
      content: 'Test post one',
      likes: 0
    },
    1: {
      content: 'Test post two',
      likes: 0
    },
    2: {
      content: 'Test post three',
      likes: 0
    }
  }]
}

console.log(initialState)

function likeReducer(state = initialState, action ){
  switch (action.type) {
    case 'LIKE':
      return {
        likes: state.likes  + 1
      };
      default:
        return state;
  }
}

function postReducer(state = initialState, action){
  switch (action.type){
    case 'POST':
    return{
      userPosts: 'Test'
    };
    default:
      return state;
  }
}

const rootReducer = combineReducers({like: likeReducer, post: postReducer})
const store = createStore(rootReducer, applyMiddleware(logger));

const render = (Component) => {
  ReactDOM.render(
    <Provider store={store}>
      <HashRouter>
        <Switch>
          <Route exact path='/' component={Component} />
          <Route path='/profile' component={Profile} />
        </Switch>
      </HashRouter>
    </Provider>,
    document.getElementById('react-app-root')
  );
};

render(App);
/*eslint-disable */
if (module.hot) {
  module.hot.accept('./components/App', () => {
    render(App)
  });
}
/*eslint-enable */

我要访问商店的组件:

import Post from './Post';
import PropTypes from "prop-types";
import { connect } from 'react-redux';

function LiveFeed(props){

  console.log(props)

  return(
    <div className="liveFeed">
    {props.userPosts.map((post, index) =>
       <Post content={post.content}
         likes={post.likes}
         />
     )}
    </div>
  )
};

const mapStateToProps = (state) => ({
  userPosts: state.userPosts
});

export default connect(mapStateToProps)(LiveFeed);

我收到关注控制台错误

  

未捕获的TypeError:无法读取未定义的属性“ map”

我有this.props.userPostsprops.userPostsuserPosts等的不同变体,无济于事。

3 个答案:

答案 0 :(得分:2)

正在建立连接,只是您的userPosts状态实际上应该在state.post.userPosts下,而不是state.userPosts-在您指定的combineReducers调用中状态应位于post子树下。

尝试将state.userPosts中的state.post.userPosts修改为mapStateToProps,您应该会看到它起作用。

注意,您还需要相应地修改initialState的结构-您应该在其中拥有一个like对象和一个post对象,然后仅将相关的子树作为适当的reducer中的初始状态:

const initialState = {
  post: {
    userPosts: [{
      0: {
        content: 'Test post one',
        likes: 0
      },
      1: {
        content: 'Test post two',
        likes: 0
      },
      2: {
        content: 'Test post three',
        likes: 0
      }
    }]
  },
  like: {
    likes: 0
  }
}

更多说明-可能实际上是您希望state.userPosts存在,如果是这种情况,则应该重新设计化径器结构-做类似的事情

const rootReducer = combineReducers({ userPosts: postReducer, ... })

只需让postReducer返回帖子数组,而不是返回具有字段userPosts的对象。

答案 1 :(得分:0)

您需要将您的商店作为商店从Provider提供给react-redux。可以这样完成:

ReactDOM.render(
  <Router history={history}>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </Router>,
  document.getElementById('root')
)

https://react-redux.js.org/api/provider

答案 2 :(得分:0)

您的化简器具有不同的状态对象,并且应具有不同的initialStates。在您的mapStateToProps函数中,添加一个console.log(state),您将明白我的意思。在同一功能中,您将要引用state.post.userPosts