【问题标题】:Why am I unable to access a Redux store in a child React component?为什么我无法访问子 React 组件中的 Redux 存储?
【发布时间】:2023-03-19 05:50:01
【问题描述】:

我试图了解如何将我的 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);

我收到以下控制台错误

未捕获的类型错误:无法读取未定义的属性“地图”

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

【问题讨论】:

  • 不少related posts,以防他们有帮助。
  • 您尝试过记录state.userPosts 吗? const mapStateToProps = (state) =&gt; { console.log(state); return {userPosts: state.userPosts} };我相信你已经正确设置了。
  • 您可以尝试在您的渲染方法中添加 JSON.stringigy(this.props.userPosts)。如果 DOM 上没有任何显示,那么您就知道信息不是从 reducer 发送的。
  • 在我的 reducer 发送对象而不是数组之前,我遇到了这个错误。您不能在对象上映射。

标签: reactjs react-redux


【解决方案1】:

您需要将您的商店作为商店提供给来自react-reduxProvider。这可以像这样完成:

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

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

【讨论】:

  • 感谢您的回复 - 我确实有通过 Provider 提供的商店。
  • 在这种情况下,我建议也显示该代码。
【解决方案2】:

它正在连接,只是您的userPosts 状态实际上应该在state.post.userPosts 之下,而不是state.userPosts - 在combineReducers 调用中,您已经指定该帖子状态应该在post 之下子树。

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

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

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 的对象。

【讨论】:

  • 您能详细说明一下它的外观吗?我的状态只是一个名为“userPosts”的对象数组,所以我不想将它映射到道具吗?
  • 这是您注销时的 initialState 对象,但随后您会做两件事,1)您将相同的 initialState 对象提供给两个不同的减速器,以及 2)更改减速器的名称(因此嵌套状态对象)在您对combineReducers 的调用中“喜欢”和“发布”。第一个是非常非正统的,除非您真的知道自己在做什么,否则我不建议您这样做。
  • @JackCollins 修改了我的答案,以根据减速器设置向您展示您的状态的结构 - 即您想要state.post.userPosts。这是否是你想要的结构是一个不同的问题——但这就是你从上面的代码中得到的,这就是为什么 state.userPosts 未定义——它不存在
  • @davincwil - 我明白了,谢谢你的帮助 - 你让我走上了正轨!
【解决方案3】:

你的 reducer 有不同的 state 对象,应该有不同的 initialStates。在你的mapStateToProps 函数中,添加一个console.log(state),你就会明白我的意思了。在同一个函数中,您需要引用 state.post.userPosts

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 2021-04-17
    • 2020-05-26
    • 2015-09-22
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2019-02-27
    • 2016-12-25
    相关资源
    最近更新 更多