首页 > 解决方案 > 在本机反应中,我如何等待 redux 命令更改存储以完成执行,然后再触发 firebase 上的更新

问题描述

我基本上正在开发一个人们可以提问的应用程序。因此,当用户发布新问题时,我会更新我的 redux 商店。然后我将更改推送到 firebase。但问题是新的更改并没有反映在 firebase 中,因为 redux 更新需要一些时间,并且到那时 firebase 更新函数已经被调用。我该如何改变?

我更新商店并调用 firebase 更新的代码。

this.props.newQuestion(this.state.addedData);
    console.log("Hello there " + JSON.stringify(this.props.user));
    let temp = this.props.user;
    console.log("This is  temp" + JSON.stringify(temp));

    firestore()
      .collection("users")
      .doc(this.props.user.id)
      .update({
        user: temp,
      })
      .then(() => {
        console.log("From the then" + JSON.stringify(this.props.user));
        console.log("User updated!");
      })
      .catch((err) => {
        console.log(err);
      });

为这个 redux 更新功能定义我的调度程序 -

case ADD_QUESTION:
      //console.log("From the actions" + JSON.stringify(action.question));
      return {
        ...state,
        user: {
          id: state.user.id,
          name: state.user.name,
          email: state.user.email,
          courses: state.user.courses,
          // adding the new question everytime
          questions: state.user.questions.concat(action.question),
        },
      };

标签: firebasereact-nativereduxgoogle-cloud-firestore

解决方案


Tushar ,如果遵循 Kokovin Vladislav 的这个想法和回答,请检查。出链接以及他在link-2-answer下方的答案

component should be updated to receive new props.

there are ways to achieve your goal:

1. componentDidUpdate check if value is changed, then do something..

 componentDidUpdate(prevProps){
     if(prevProps.value !== this.props.value){ alert(prevProps.value) }
  }
2. redux-promise ( middleware will dispatch the resolved value of the promise)

export const updateState = (key, value)=>
Promise.resolve({
  type:'UPDATE_STATE',
  key, value
})
then in component

this.props.dispatch(updateState(key, value)).then(()=>{
   alert(this.props.value)
})
2. redux-thunk

export const updateState = (key, value) => dispatch => {
  dispatch({
    type: 'UPDATE_STATE',
    key,
    value,
  });
  return Promise.resolve();
};
then in component

this.props.dispatch(updateState(key, value)).then(()=>{
   alert(this.props.value)
})

希望对您有所帮助,这个答案解释得很好。


推荐阅读