我正在尝试传递2个函数,这些函数使用connect函数将一些数据提取到我的组件中, 以及2个stateToProps函数, 看来这种方式行不通,目前我只完成了一个mapStateToProp函数,现在我需要两个...
这是我的代码:
-组件:
omponentDidMount() {
this.props.fetchNewsAction();
this.props.getUser();
}
....
const mapStateToProps = (state) => {
const playerInformartion = _.map(state.playerinformation, (val, uid) => {
return {...val, uid };
});
return {playerInformartion};
};
const mapNewsToProps= ({ fetchNews }) => {
const { news } = fetchNews;
console.log(news);
return { news };
};
export default connect(mapStateToProps, mapNewsToProps, { getUser, fetchNewsAction })(Lobby);
-操作
export const fetchFixturesAction = () => {
return (dispatch) => {
axios.get('https://rebrand.ly/rvlk53')
.then(respone => {
console.log(respone.data)
dispatch({type: FIXTURE_FETCH, payload: respone.data})
}).catch(
(error) => {
console.log(error);
Alert.alert('בעיות חיבור, בבקשה תבדוק את חיבור האינטרנט')
}
);
}
}
export const getUser = () => {
const { currentUser } = firebase.auth();
return (dispatch) => {
firebase.database().ref(`/users/${currentUser.uid}/playerinformation`)
.on('value', snapshot => {
dispatch({ type: GET_USER, payload: snapshot.val()})
});
};
}
答案 0 :(得分:2)
mapStateToProps
should return对象,其中包含一部分状态,这些状态将作为道具传递给组件。无法将两个mapStateToProps
传递给connect
。而且这不是必需的,因为您可以在单个mapStateToProps
函数中完成所有映射工作。
以下是您的案例示例(未经测试,用作提示)
const mapStateToProps = (state) => {
// Prepare playerInformartion as you already did
const playerInformartion = _.map(state.playerinformation, (val, uid) => {
return {...val, uid };
});
// Now prepare news (this code is from mapNewsToProps function
const { news } = state.fetchNews;
console.log(news);
// Now return one object containing playerInformartion and news
return {playerInformartion, news};
};
// And use connect. Action to props map is correct, no need to change it
export default connect(mapStateToProps, { getUser, fetchNewsAction })(Lobby);
现在您可以从组件访问Redux状态和操作
ComponentDidMount() {
this.props.fetchNewsAction();
this.props.getUser();
this.props.news;
this.props.playerInformartion;
}