1。有人在我做错事情的地方可以帮助我吗? 2.我正在将状态映射到其属性的组件,但我仍然得到这个 错误“未定义mapStateToProps” 这是下面的整个组成部分。错误显示为“未定义mapStateToProps”
import React, {Component} from 'react';
import Icon from 'react-native-vector-icons/EvilIcons';
import { loadInitialPosts} from './actions';
import {connect } from 'react-redux';
import _ from 'lodash';
import {View, StyleSheet,FlatList} from 'react-native';
import PostItem from './PostItem';
import PostDetail from './PostDetail';
class PostsList extends Component {
componentWillMount() {
this.props.loadInitialPosts();
}
renderItem({item}){
return <PostItem posts = { item } />;
}
renderInitialView(){
if(this.props.postDetailView === true){
return(
<PostDetail />
);
}
else{
return(
<FlatList
data={this.props.posts}
renderItem={this.renderItem} />
)}
}
render(){
return(
<View style={styles.list}>
{this.renderInitialView()}
</View>
);
}
}
const mapStateToProps = state => {
const posts = _.map(state.posts, (val, id) =>
{
return { ...val, id};
});
return{
posts: posts,
postDetailView: state.postDetailView,
};
}
export default connect(mapStateToProps, { loadInitialPosts })(PostsList)
1。这是调度数据的动作
export const loadInitialPosts = () => {
return function(dispatch){
return axios.get(apiHost
+"/api/get_posts?
count=20")
.then((response) => {
dispatch({ type:
'INITIAL_POSTS_FETCH', payload:
response.data.posts});
}).catch((err) => {
console.log(err);
});
};
};
答案 0 :(得分:0)
mapStateToProps
在export default connect(mapStateToProps)(SomeClass)
之前位于课程之外
class SomeClass extends React.Component {
...
}
const mapStateToProps = state => {
const posts = _.map(state.posts, (val, id) => {
return { ...val,
id
};
});
return {
posts: posts,
postDetailView: state.postDetailView,
};
}
答案 1 :(得分:0)
要消除未定义mapStateToProps
的可能性,请考虑直接在对mapStateToProps
的调用中定义connect()
,如下所示:
class PostsList extends React.Component {
componentWillMount() {
this.props.loadInitialPosts();
}
renderItem({item}){
return <PostItem posts = { item } />;
}
renderInitialView(){
if(this.props.postDetailView === true){
return <PostDetail />;
}
else{
return <FlatList
data={this.props.posts}
renderItem={this.renderItem} />
}
}
render(){
return(<View style={styles.list}> {this.renderInitialView()} </View>);
}
}
/*
Avoid declaration of mapStateToProps object by defining this object
directly in the call to connect()
*/
export default connect((state => {
return {
posts : state.posts.map((val, id) => ({ ...val, id })),
postDetailView: state.postDetailView,
}
}), { loadInitialPosts })(PostsList)