Redux状态从第一次开始不更新

时间:2020-07-19 14:10:57

标签: javascript reactjs typescript react-native redux

也许这是一个愚蠢的问题,但是我有一个问题。我的状态如下:

const initialState: PhotoState = {
  photos: [],
};

reducer代码如下:

const initialState: PhotoState = {
  photos: [],
};

export default function photoReducer(state = initialState, action: PhotoActionTypes): PhotoState {
  switch (action.type) {
    case SET_PHOTOS:
      const photos: any[] = action.payload;
      return {...state, photos};
  }

  return state;
};

我从API获取照片,然后以这种方式设置它们:

export function setPhotos(payload: any[]): PhotoActionTypes {
  return {type: SET_PHOTOS, payload};
}

export function getPhotos() {
  return (dispatch: Dispatch<PhotoActionTypes>, getState: () => RootState): void => {
    const profile_id = getState().auth.profile_id;
    ax().post('pictures/api/pictures/list', {profile_id}).then((response) => {
      const photos: any[] = response.data.pictures || [];
      dispatch(setPhotos(photos));
    })
  }
}

我还有一个动作,可以将新照片发送到服务器并将其保存在历史记录中。然后我在组件中得到照片:

useEffect(() => {
    dispatch(getPhotos());
  }, []);

const handleSendPhoto = (): void => {
    dispatch(sendPhoto(image?.base64));
    dispatch(getPhotos());
  }

整个组件:

const PhotoScreen = () => {
  const [photoFlag, setPhotoFlag] = useState(false);
  const [image, setImage] = useState<TakePictureResponse | null>(null);
  const [height, setHeight] = useState(0);
  const width = Dimensions.get('screen').width / 5;
  const dispatch = useDispatch();

  const handleSendPhoto = (): void => {
    dispatch(sendPhoto(image?.base64, location));
    dispatch(getPhotos());
  }

  const PhotoView = () => (
    <View>
      <FastImage
        style={{width: width, height: height}}
        source={{
          uri: `data:image/jpeg;base64, ${image?.base64}`,
          priority: FastImage.priority.normal,
        }}
        resizeMode={FastImage.resizeMode.contain}
        onLoad={evt => {
          setHeight(evt.nativeEvent.height / evt.nativeEvent.width * width)
        }}
      />
      <Button
        mode="contained"
        onPress={handleSendPhoto}
        disabled={!image}
        color={constants.buttonColor}>
        Add photo
      </Button>
    </View>
  );

  return (
    <SafeAreaView style={{...mainStyles.screen, ...styles.container}}>
      <StatusBarDark />
      {!photoFlag && (<View>
        <Button
          mode="contained"
          onPress={() => setPhotoFlag(true)}
          color={constants.buttonColor}>
          Make photo
        </Button>
      </View>)}

      {photoFlag && <CameraComponent setImage={setImage} setPhotoFlag={setPhotoFlag}/>}
      {image !== null && <PhotoView />}
    </SafeAreaView>
  );
};

export default PhotoScreen;

但是状态仅从第二次开始更新。我按下“添加照片”按钮,照片会追加到历史记录中,但不会显示在历史记录中。然后,我再次按下按钮,历史照片中会显示上一张照片,但当前照片中没有。

我该如何解决?

UPD:问题已解决。该问题可能已经结束。

1 个答案:

答案 0 :(得分:1)

您不应该这样做,因为两个呼叫将同时发送:

const handleSendPhoto = (): void => {
  dispatch(sendPhoto(image?.base64));
  dispatch(getPhotos()); // this will be called before the upload is finished. so the old data will be returned.
}

您可能需要使用redux-thrunk(https://github.com/reduxjs/redux-thunk),如下所示:

const handleSendPhoto = (): void => {
  dispatch(sendPhoto(image?.base64)).then(() => dispatch(getPhotos()));
}