【问题标题】:How to Save Redux State First before continuing?如何在继续之前先保存 Redux 状态?
【发布时间】:2019-06-25 15:47:52
【问题描述】:

我有一个项目在 React Native 中使用了 React-redux 和 Redux-persist:

这些是我主要使用的依赖项: “世博”:“^32.0.0”, “反应”:“16.5.0”, "redux": "^4.0.1", "react-redux": "^5.1.1", "redux-persist": "^5.10.0"

我想让 redux 先存储数据,然后将屏幕导航到另一个导航器。所以我尝试使用异步功能,结果它不起作用。但如果我不使用异步功能,它完全可以正常工作,但没有导航。

那为什么要使用异步呢?因为在 Redux 从服务器保存我的用户信息之前,屏幕已经移动到另一个导航器,并且 redux 没有设法保存用户信息

这就是我在 LoginScreen 中调用 redux 操作的方式:

.then((responseJson) => {
        console.log("Server Response: ", responseJson.data)

        this.storeUserInformation(responseJson.data).then(() => {
          this.toggleLoading()
          this.props.navigation.navigate('AppNavigator')
        })   
    })

storeUserInformation = async (userInformation) => {
  await this.props.saveUserInformation(userInformation)
}
const INITIAL_STATE = {
  userAccountInformation: {},
  userExpoToken: {},
}

const reducer = (state = INITIAL_STATE, action) => {

  switch(action.type){
    case USER_LOGIN:
      console.log("UserAccountReducer", "calling USER_LOGIN")
      return { userAccountInformation: action.payload.members }
    case SAVE_USER_INFORMATION:
      console.log("UserAccountReducer", "calling SAVE_USER_INFORMATION")
      return { userAccountInformation: action.payload }
    case USER_LOGOUT:
      console.log("UserAccountReducer", "calling USER_LOGOUT")
      return {state : {}}
    case SAVE_EXPO_TOKEN:
      console.log("UserAccountReducer", "calling SAVE_EXPO_TOKEN")
      return { userExpoToken: action.payload }
    default:
    console.log("UserAccountReducer", "no Action Called")
      return state
  }
}

export default reducer

没有异步的东西,我的操作可以将信息从服务器保存到 redux 存储。但是因为在我调用this.props.navigate之后,action还没有完成保存过程,还没完成就移动到另一个页面

我想让redux先从服务器保存数据,然后在保存数据后导航到下一个屏幕

【问题讨论】:

    标签: reactjs react-native redux react-redux redux-persist


    【解决方案1】:

    在你的 reducer 中设置一个初始状态,比如 isDataLoaded 设置为默认 false

    当数据从 API 到达时,在适当的 reducer 情况下将 isDataLoaded 的值设置为 true

    然后在您的componentWillReceivePropscomponentDidUpdate 中检查是否条件

    if(this.props.isDataLoaded){
       // your data is stored now you can do here navigate things
    }
    

    不要忘记将状态映射到该状态的道具isDataLoaded

    【讨论】:

    • 感谢您的回复。但是有没有其他方法可以在不使用 componentWillReceiveProps 的情况下巧妙地做到这一点?
    • 我们想要执行一些或一行代码,因此应该有一个方法正在监听 reducer props,当你想要的 props 得到一个值时,这个方法应该被执行。 componentWillReceivePropscomponentWillReceiveProps 允许您这样做。所以,据我所知,这是实现这一目标的唯一方法,是的,redux 看起来有些棘手,但相信我,一旦你知道如何做到这一点,你就会做最简单的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多