【发布时间】: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.userPosts、props.userPosts、userPosts 等的不同变体,但无济于事。
【问题讨论】:
-
不少related posts,以防他们有帮助。
-
您尝试过记录
state.userPosts吗?const mapStateToProps = (state) => { console.log(state); return {userPosts: state.userPosts} };我相信你已经正确设置了。 -
您可以尝试在您的渲染方法中添加 JSON.stringigy(this.props.userPosts)。如果 DOM 上没有任何显示,那么您就知道信息不是从 reducer 发送的。
-
在我的 reducer 发送对象而不是数组之前,我遇到了这个错误。您不能在对象上映射。
标签: reactjs react-redux