首页 > 解决方案 > 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
    };
}

标签: react-nativereduxasync-awaitnested-object

解决方案


可能是变量名冲突?从我所见,您已经使用了setPhotos您的操作名称并设置了本地组件状态。

当您调用dispatch(setPhotos(photos))它时,它会尝试调度 local setPhotos,而不是您的 redux 操作,因此会出现错误。


推荐阅读