我正在制作一个表单,在其中键入要搜索的电影标题,然后从拥有所有电影的状态取回电影。我目前正在尝试创建一个选择器,该选择器仅从州中选择电影,其标题与搜索查询相同。我在mapStateToProps
组件的<MovieForm />
中调用了选择器方法,这在本教程中已经看到,但是我认为在初始状态渲染时会出错。
我尝试在选择器以及mapState的props上使用if语句,以便在状态未定义时返回状态,但仍然会收到错误。
编辑:此错误最初是在运行任何GET_MOVIE_SUCCESS之前
selectors.js
export function selectMovieFromMovies(state, title) {
return {
moviesById: state.moviesById.map(movie => movie.title.toString() === title)
};
}
MovieForm.js
const mapStateToProps = (state, title) => {
console.log("state in mapState:", state);
return {
moviesById: selectMovieFromMovies(state, title)
};
};
reducer的相关部分:movies.js
const initialState = {
moviesById: []
};
function movieReducer(state = initialState, action) {
switch (action.type) {
case "GET_MOVIE_SUCCESS":
console.log("action.json.movies:", action);
return {
...state,
moviesById: action.json.movies
};
浏览器错误:
Uncaught TypeError: Cannot read property 'map' of undefined
at selectMovieFromMovies (selectors.js:4)
at Function.mapStateToProps [as mapToProps] (MovieForm.js:43)
答案 0 :(得分:0)
此示例未直接使用Redux,但原理应成立。
您确定派发GET_MOVIE_SUCCESS
操作时是否正确设置了电影吗?在某个时候它正变得undefined
:
function selectMovieFromMovies(state, title) {
return {
moviesById: state.moviesById.map(movie => movie.title.toString() === title)
};
}
const mapStateToProps = (state, title) => {
console.log("state in mapState:", state);
return {
moviesById: selectMovieFromMovies(state, title)
};
};
const initialState = {
moviesById: []
};
function movieReducer(state = initialState, action) {
switch (action.type) {
case "GET_MOVIE_SUCCESS":
console.log("action.json.movies:", action);
return {
...state,
moviesById: action.json.movies
};
default:
return state;
}
}
let state = movieReducer(undefined, {
type: "INIT"
});
console.log(state);
let mapState = mapStateToProps(state, "anything");
console.log(mapState);
state = movieReducer(state, {
type: "GET_MOVIE_SUCCESS",
json: {}
});
console.log(state);
mapState = mapStateToProps(state, "anything"); // throws: Cannot read property 'map' of undefined
console.log(mapState);
答案 1 :(得分:0)
我没有输入正确的状态路径。感谢@CodeManiac提供解决方案
selectors.js之前
export function selectMovieFromMovies(state, title) {
return {
moviesById: state.moviesById.map(movie => movie.title.toString() === title)
};
}
selectors.js之后
export function selectMovieFromMovies(state, title) {
return {
moviesById: state.movieReducer.moviesById.map(movie => movie.title.toString() === title)
};
}