React/Redux... Error: Actions must be plain objects. Use custom middleware for async actions

React/Redux... Error: Actions must be plain objects. Use custom middleware for async actions

我有一个由照片网格组成的组件,用户可以在其中单击一个单元格以从相机胶卷上传图像。组件状态是一个具有一系列键值对的对象,键是索引,值本身是一个具有图像 属性 的对象。照片上传和删除时状态正在正确更新,只是当我调用 dispatch 时出现错误。

类似的问题涉及到人们在 async 函数中调用 dispatch 或使用 await 但我在这里没有声明。

这在过去一天一直困扰着我,我觉得我遗漏了一些非常明显的东西,所以我很感激任何帮助。

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)) 时,它试图调度本地 setPhotos,而不是您的 redux 操作,因此出现错误。