我试图了解如何将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.userPosts
,props.userPosts
,userPosts
等的不同变体,无济于事。
答案 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')
)
答案 2 :(得分:0)
您的化简器具有不同的状态对象,并且应具有不同的initialStates。在您的mapStateToProps
函数中,添加一个console.log(state)
,您将明白我的意思。在同一功能中,您将要引用state.post.userPosts
。