切片函数应用于未定义
2019-11-06
249
我正在开发一个 React 应用,当我在输入字段中输入一些文本时,该字段应与城市列表匹配。
我创建了一个操作并接受两个输入(列表和城市),我应用了
list.slice()
并检查了该值。当我在输入字段中输入另一个字符时,它显示
error
,表示切片应用于
undefined
。
//app.js
inputHandler = event => {
event.preventDefault();
let val = event.target.value;
this.props.onCitySearch(this.props.cityList, val);
};
const mapStateToProps = state => {
return {
cityList: state.cities.citylist,
citiesSearched: state.cities.citySearched
};
};
const mapDispatchToProps = dispatch => {
return {
onFetch: () => dispatch(actions.fetchCities()),
onCitySearch: (list, city) => dispatch(actions.citySearched(list, city))
};
};
//actions.js
export const fetchCities = () => dispatch => {
fetch("http://localhost:8000/cities")
.then(res => res.json())
.then(data => {
return dispatch({
type: "FETCHCITIES",
cities: data
});
});
};
export const citySearched = (list, city) => dispatch => {
console.log(list);
const cities = list.filter(c => {
return c.name.toLowerCase().includes(city.toLowerCase());
});
localStorage.setItem("cities", JSON.stringify(cities));
return dispatch({
type: "CITIESSEARCHED",
city: cities
});
};
//citiesReducer
const initialState = {
citylist: [],
citySearched: []
};
const citiesReducer = (state = initialState, action) => {
switch (action.type) {
case "FETCHCITIES":
return {
...state,
citylist: action.cities
};
case "CITIESSEARCHED":
return {
citySearched: action.city
};
default:
return {
...state
};
}
};
export default citiesReducer;
1个回答
使用 .filter 代替 .slice
const citySearched= (list, city)=> (dispatch)=>{
const cities = list.filter((xyz) => {
return xyz.toLowerCase().includes(city.toLowerCase());
});
localStorage.setItem("cities",JSON.stringify(cities));
return dispatch({
type: 'CITIESSEARCHED', city: cities
});
};
Deep Govani
2019-11-06