我正在尝试使用redux显示react组件中的帖子列表,但是我收到以下警告:
警告:propType失败:posts
中未指定必需的道具Posts
。检查PostsContainer
的呈现方法。
我有以下代码:
帖子容器:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { getInitalPosts } from 'actions/postsActions'
import { Link } from 'react-router'
import _ from 'lodash'
import Posts from 'components/PostApp/Posts'
class PostsContainer extends Component {
static fetchData({ store }) {
return store.dispatch(getInitalPosts())
}
componentDidMount() {
this.props.getInitalPosts()
}
render() {
return (
<div>
<h2>Posts</h2>
<Posts posts={this.props.posts} />
<Link to="/">Back to Home</Link>
</div>
)
}
}
function mapStateToProps (state) {
return { posts: state.posts }
}
export { PostsContainer }
export default connect(mapStateToProps, { getInitalPosts })(PostsContainer)
和帖子组件:
import React, { Component, PropTypes } from 'react'
import { List } from 'immutable'
class Posts extends Component {
render() {
return (
<div>
Posts component
{
this.props.posts
}
</div>
)
}
}
Posts.propTypes = {
posts: PropTypes.instanceOf(List).isRequired
//posts: PropTypes.posts
}
export default Posts
我做错了什么?
[编辑]
这是帖子缩减器:
import * as ActionType from 'actions/postsActions'
import Immutable from 'immutable'
let defaultState = Immutable.fromJS([])
function postsReducers (state = defaultState, action) {
switch(action.type) {
case ActionType.INITIAL_POSTS:
return Immutable.fromJS(action.response)
break
default:
return state
}
}
export default postsReducers
就导入容器而言,它位于路径索引中:
8 import Questions from 'containers/Questions'
9 import Question from 'containers/Question'
10: import Posts from 'containers/Posts'
11
12 export default function(history) {
..
14 <Router history={history}>
15 <Route path="/" component={App}>
16: <Route path="posts" component={Posts} />
17 <Route path="questions" component={Questions} />
18 <Route path="questions/:id" component={Question} />
答案 0 :(得分:2)
您如何导入PostsContainer
?
如果您这样做:
import { PostsContainer } from PostsContainer;
您无法导入connect
版本,因此您不会尝试在posts
内使用PostsContainer
道具。< / p>
您可以发布导入代码吗?
答案 1 :(得分:0)
由于您在getInitialPosts
componentDidMount
PostsContainer
上运行this.props.posts
,因此第一次呈现时它还没有任何帖子,因此{{1}的值是null
。这是传递给Posts
的内容,违反了propTypes
要求。
您可以在if
render
方法中添加PostsContainer
语句,仅在有帖子的情况下呈现Posts
,否则呈现加载微调器。
答案 2 :(得分:0)
问题在于我的reducer文件的名称。它必须匹配您在组件中指定的变量名称。
在文档中提及。