【发布时间】:2021-02-06 21:58:15
【问题描述】:
我尝试了几个小时,但无法弄清楚为什么在添加 自定义对象的 array 后没有调用我的状态。
// In my component...
const myRemoteArray = getRemoteArray() // Is working
props.addAdItems(myRemoteArray) // Calls **1 via component.props
/// ...
const mapDispatchToProps = (dispatch) => {
return {
addAdItems: (items) => { // **1
// Items contains my array of objects
dispatch(addAdItems(items)) // Calls **2
},
}
}
// My action
export const addAdItems = (items) => { // **2
// Items contains my array of objects
return { // Calls **3
type: AD_ITEMS,
adItems: items,
}
}
const productsReducer = (state = initialState, action) => {
switch (action.type) { // **3
case AD_ITEMS:
// Is working!
// action.adItems contains my array!
const _state = {
...state,
adItems: action.adItems, // Here is the issue, I am not sure how to add my NEW array to existing state and update it.
// Like that: ??? "adItems: ...action.adItems" or adItems: [action.adItems]
}
// The new state contains my Array!!!
return _state
default:
return state
}
}
// In my component... !!!!
// THIS IS NOT CALLED or it is called with empty array from initialState!!!
const mapStateToProps = (state) => {
return {
updatedItem: state.changedItem,
adItems: state.adItems,
}
}
在我看来,Redux 对包含以下数据的数组存在问题。我的类方法有 Redux 问题吗?
class Ad {
constructor(
id,
isPublished
) {
this.id = id
this.isPublished = isPublished
}
someMessage = () => { return "Help me!" }
needHelp = () => { return true }
}
我的 Redux 正在使用其他调用、数据和对象,这意味着我的 createStore 和所有其他内容都是正确的。
PS:我没有多家商店。
更新 现在我的 mapDispatchToProps 被当前数组调用,但没有持久化。
更新 2
如果我保存文件并强制刷新应用程序,props.adItems 包含 我加载的数组,但如果我想在运行时访问 props.adItems(例如在 FlatList刷新)又是空数组!
为什么? 在通过 useEffect 进行更改后,我应该将数组存储在 useState 属性中吗?
【问题讨论】:
标签: javascript reactjs react-native redux react-redux