我试图在react-redux中返回一个数组,但是当我尝试将它们放入我的react组件时却变得不确定。
如何使用“ GET_TODO”,“ GET_FINISHED”,“ GET_LATER”大小写返回数组。
const initialState = {
today: [1, 2, 3],
finished: [3, 2, 1, 3],
later: [2, 3, 1, 4, 2, 5]
};
export default (state = initialState, action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state.today, action.payload]
case 'DELETE_TODO':
return state.today.filter((item, index) => index !== action.payload)
case 'GET_TODO':
return state.today
case 'ADD_LATER':
return [...state, action.payload]
case 'DELETE_LATER':
return state.filter((item, index) => index !== action.payload)
case 'GET_LATER':
return [...state.later]
case 'ADD_FINISHED':
return [...state, action.payload]
case 'DELETE_FINISHED':
return state.filter((item, index) => index !== action.payload)
case 'GET_FINISHED':
return [...state.finished]
default:
return state;
}
}
componentDidMount() {
this.props.get();
}
function mapStateToProps(state) {
return {
today: state.important.today ? state.important.today : [],
finished: state.important.finished ? state.important.finished : [],
later: state.important.later ? state.important.later : [],
}
}
function mapDispatchToProps(dispatch) {
return {
add: (value) => {
dispatch({ type: 'ADD_TODO', payload: value })
},
remove: (index) => {
dispatch({ type: 'DELETE_TODO', payload: index })
},
get: () => {
dispatch({type:'GET_TODO'})
},
addToFinished: (value) => {
dispatch({ type: 'ADD_FINISHED', payload: value })
},
removeFinished: (index) => {
dispatch({ type: 'DELETE_FINISHED', payload: index })
},
addToLater: (value) => {
dispatch({ type: 'ADD_LATER', payload: value })
},
removeLater: (index) => {
dispatch({ type: 'DELETE_LATER', payload: index })
}
}
}
答案 0 :(得分:0)
您的某些动作正在由减速器处理,这将导致您变得不确定。由于您的对象上有多个键,因此需要确保只处理有问题的键,例如:
case 'DELETE_LATER':
return state.filter((item, index) => index !== action.payload)
应该是:
case 'DELETE_LATER':
return {
...state,
later: state.later.filter((item, index) => index !== action.payload)
}
再举一个例子,您的ADD_TODO处理程序将引起问题:
const initialState = {
today: [1, 2, 3],
finished: [3, 2, 1, 3],
later: [2, 3, 1, 4, 2, 5]
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state.today, action.payload]
case 'DELETE_TODO':
return state.today.filter((item, index) => index !== action.payload)
case 'GET_TODO':
return state.today
case 'ADD_LATER':
return [...state, action.payload]
case 'DELETE_LATER':
return state.filter((item, index) => index !== action.payload)
case 'GET_LATER':
return [...state.later]
case 'ADD_FINISHED':
return [...state, action.payload]
case 'DELETE_FINISHED':
return state.filter((item, index) => index !== action.payload)
case 'GET_FINISHED':
return [...state.finished]
default:
return state;
}
}
const newState = reducer(initialState, { type: 'ADD_TODO', payload: 3})
console.dir(newState)
请注意,您现在已经丢失了状态中的其他密钥。
作为附加注释,当您返回数组时,代码:
return [...array]
等效于:
return array