Redux 状态改变,但当我回到屏幕时组件不会重新渲染

时间:2021-02-11 11:32:51

标签: javascript reactjs react-native redux global-state

我有两个屏幕,A 和 B。它们都使用相同的全局状态

<Text style={Styles.textScoreHeader}>{this.props.profleInfos.Points}</Text>

使用这个:

const mapStateToProps = (state) => {
  return {
    folder: state.account.folder,
    theme: state.account.theme,
    whichAccount: state.account.whichAccount,
    profleInfos: state.account.profleInfos,
  };
};
export default connect(mapStateToProps)(ScreenA);

对于屏幕 A 和:

const mapStateToProps = (state) => {
  return {
    folder: state.account.folder,
    theme: state.account.theme,
    whichAccount: state.account.whichAccount,
    profleInfos: state.account.profleInfos,
  };
};
export default connect(mapStateToProps)(ScreenB);

对于屏幕 B。

在屏幕 A 中,我单击一个按钮转到屏幕 B,在那里我更改 profleInfos.Points 全局状态,如下所示:

_Transaction(folder, apiName, code) {
  Transaction(folder, apiName, code).then(data => {
    if (data.success) {
      var theProfleInfos = this.props.profleInfos 
      theProfleInfos.Points = data.LoyPoints //changing profleInfos.Points
      const actionProfileInfos = { type: "SET_PROFILE_INFOS", value: theProfleInfos }
      this.props.dispatch(actionProfileInfos) // dispatch the action
    }
    this.setState({ scanningResponse: data, isLoading: false })
  })
};

我使用 this.props.dispatch(actionProfileInfos) 而不是 mapdispatchtoprops(告诉我是否必须这样做,但我更喜欢这种方法)。
在此屏幕 (B) 中,我显示 this.props.profleInfos.Points 并且它工作正常(扫描后值发生变化)但是当我返回屏幕 A(后退按钮)时,this.props.profleInfos.Points 不会刷新。< /p>

附注。我在抽屉里有相同的值,如果我打开抽屉,我可以看到相同值的变化,也许是因为我“打开”了抽屉

1 个答案:

答案 0 :(得分:0)

我能够在屏幕 A 中使用 useFocusEffect 解决问题:此链接帮助了我see the class component part

这是我的代码:

   import { useFocusEffect } from '@react-navigation/native';

function Reloader({ api }) {
  useFocusEffect(
    React.useCallback(() => {
      api();
    }, [])
  );
  return null;
}

// ...

class ScreenA extends React.Component {
  // ...

  _getProfileInfo(folder, apiName, LoyPhone, LoyRef, LoyCardNum) {
    getPeintreInfo(folder, apiName, LoyPhone, LoyRef, LoyCardNum).then(data => {
      const actionProfileInfos = { type: "SET_PROFILE_INFOS", value: data }
      this.props.dispatch(actionProfileInfos)
    })
  }

  render() {
    return (
        <>
        <Reloader
          api={() => this._getProfileInfo(this.props.folder, 'GetProfileInfos.php', 'empty', 1, 'empty') />
            {/* rest of ScreenA component */ }
        </>
      );
    }
  }