react-native - React/Redux... 错误:操作必须是普通对象。使用自定义中间件进行异步操作
问题描述
我有一个由照片网格组成的组件,用户可以单击一个单元格从相机胶卷上传图像。组件状态是具有一系列键值对的对象,键是索引,值本身是具有图像属性的对象。照片上传和删除时状态正在正确更新,只是当我调用调度时,我得到一个错误。
类似的问题涉及人们在异步函数中调用调度或使用等待,但我在这里没有声明。
最后一天这让我很恼火,我觉得我错过了一些非常明显的东西,所以我很感激任何帮助。
const PhotoUpload = ({ navigation }) => {
const [photos, setPhotos] = useState(
{'0' : {image: null},
'1' : {image: null},
'2' : {image: null},
'3' : {image: null},
'4' : {image: null},
'5' : {image: null}}
)
const dispatch = useDispatch();
dispatch(setPhotos(photos)); // Error: Actions must be plain objects. Use custom middleware for async actions.
...
return (
<>
<SortableGrid >
{
Object.keys(photos).map((key) =>
// image is not showing
<View key={ key } fixed={photos[key].image === null ? true : false} onTap={() => this.pickSingle(true, false, key)} style={ styles.itemContainer } >
<Image defaultSource={ require('./default-avatar.png') } source={ getPhoto(key) } style={ styles.itemImage } />
{ photos[key].image != null
? <TouchableOpacity onPress={() => deletePhoto(key)} style={styles.deleteButton} >
<Icon name={"ios-remove"} size={20} color="#ff0000" />
</TouchableOpacity>
: null
}
</View>
)
}
</SortableGrid>
</>
)
这是我的减速机:
const INITIAL_STATE = {
user: {
name: "",
gender: "",
birthdate: "",
photos: {},
}
}
const userReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'SETPHOTOS':
return {
// likely incorrect logic here
...state,
user: {
...state.user,
photos : state.user.photos.concat(action.payload)
}
}
default:
return state
}
};
和行动:
export const setPhotos = (receivedPhotos) => {
console.log(receivedPhotos)
return{
type: 'SETPHOTOS',
payload: receivedPhotos
};
}
解决方案
可能是变量名冲突?从我所见,您已经使用了setPhotos
您的操作名称并设置了本地组件状态。
当您调用dispatch(setPhotos(photos))
它时,它会尝试调度 local setPhotos
,而不是您的 redux 操作,因此会出现错误。
推荐阅读
- javascript - 未捕获(承诺):错误:Angular JIT 编译失败:'@angular/compiler' 未加载!在角度 9
- linux - 我收到“网络错误:连接超时”错误
- javascript - React.js 中这三种语法有什么区别?
- javascript - 在 vuex store 或 getter 中访问 vue 或 vuetify 实例
- html - 为什么我的 html 到 WordPress 转换主题的菜单不显示?
- vb.net - DrawString 上的文本未居中 vb.net
- typescript - NestJS:管道未应用于绑定的主体参数
- typescript - 打字稿错误地将元组推断为数组
- javascript - 在同一浏览器和新标签中打开 Cookie 横幅“隐私声明”
- javascript - 比较时间和日期是否包括在内?