我是个新手,我想从几个动作中获取数据-在一个组件中,所以我的目标是这样做:
假设我有一个组件名称 在它里面我想这样做:
componentWillMount() {
this.props.fetchGenres();
this.props.fetchMovies();
}
在出口区域:
AllMovies.propTypes = {
fetchMovies: propTypes.func.isRequired,
fetchGenres: propTypes.func.isRequired,
genres: propTypes.array.isRequired,
movies: propTypes.array.isRequired
};
const mapStateToProps = state => ({
genres: state.genres,
movies: state.movies.items,
newMovie: state.movies.item,
editedMovie: state.movies.item
});
export default connect(
mapStateToProps,
{ fetchMovies, fetchGenres }
)(AllMovies);
如果我在“导出默认连接”中仅使用一个映射,则不会收到任何错误-但是,当我向连接对象中添加另一个映射时,则会出现错误
所以我的问题是-这是将多个状态映射到道具的正确方法吗?
答案 0 :(得分:1)
我没有发现您的代码有什么问题,但是当您将动作创建者传递给connect的第二个参数时,也许您没有导入它们吗?它将显示类似-boolean showTraffic = false;
...
public void traffic (View view){
ImageButton bttn = findViewById(R.id.traffic);
showTraffic = !showTraffic //Flip value
mMap.setTrafficEnabled(showTraffic);
...
}
的内容。如果是这样,则是由于您试图将ReferenceError: fetchMovies is not defined
传递给{fetchMovies, fetchGenres}
函数而不是connect
中的代码而引发的。
componentWillMount()
答案 1 :(得分:1)
我总是使用“ bindActionCreators”来绑定redux动作。因此,您的代码将如下所示:
import { bindActionCreators } from 'redux';
import * as genreActionCreators from '@redux/actions/genre-actions'; // Path to the file containing the redux action fetchGenres().
import * as movieActionCreators from '@redux/actions/movie-actions'; // Path to the file containing the redux action fetchMovies().
class AllMovies extends Component {
componentWillMount() {
this.props.actions.genres.fetchGenres();
this.props.actions.movies.fetchMovies();
}
// Rest of the component code
}
AllMovies.propTypes = {
fetchMovies: propTypes.func.isRequired,
fetchGenres: propTypes.func.isRequired,
genres: propTypes.array.isRequired,
movies: propTypes.array.isRequired
};
// Subscribing the component to redux store changes.
function mapStateToProps(state) {
return {
genres: state.genres,
movies: state.movies.items,
newMovie: state.movies.item,
editedMovie: state.movies.item
};
}
// Enables the component to dispatch actions
function mapDispatchToProps(dispatch) {
return {
actions: {
movies: bindActionCreators(movieActionCreators, dispatch),
genres: bindActionCreators(genreActionCreators, dispatch),
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(AllMovies);
希望这会有所帮助。干杯!