为什么我无法在ComponentDidMount中访问状态?

时间:2017-09-13 00:57:59

标签: react-native

我有React Native的代码:

componentWillMount() {
    shiftKeys = []; // need to clear previously set data or we will get dupicate array key errors
    // get the current user from firebase
    const userData = firebaseApp.auth().currentUser;
    const profileRef = firebaseApp.database().ref('userdata').child(userData.uid);
    profileRef.on('value', snapshot => {
      if (snapshot.val().hasOwnProperty('licenseType') && snapshot.val().hasOwnProperty('licenseState') && snapshot.val().hasOwnProperty('distance')) {
        this.setState({
          licenseType: snapshot.val().licenseType,
          licenseState: snapshot.val().licenseState,
          distancePref: snapshot.val().distance,
        });
      console.log('State1', this.state.distancePref)
      } else {
        // redirect back to profile screens because we need three values above to search.
        this.props.navigation.navigate('Onboarding1')
      }
    });
  }

  componentDidMount() {
    console.log('State2', this.state.distancePref)
    var geoQuery = geoFire.query({
      center: [45.616422, -122.580453],
      radius: 1000// need to set dynamically
      });

我认为这是某种范围问题?

当我查看控制台日志时,状态1设置正确,但状态2没有打印任何内容。

在我的应用中,我需要查找用户距离偏好,然后使用它来运行查询。

如何将值从componentWillMount传递给componentDidMount?

2 个答案:

答案 0 :(得分:1)

https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle

componentWillMount中的setState - 糟糕的方式。您没有以这种方式解决问题,因为在componentDidMount之前状态不会更新(请参阅生命周期)。在构造函数中检查创建状态时的条件。 或者您可以使用redux解决问题。

答案 1 :(得分:0)

这个问题的根本问题与我不了解如何反应和反应原生渲染代码有关。

我试图从firebase获取用户信息,然后设置首选项,然后使用这些首选项来运行搜索。

我添加了redux和thunk,以便在用户有机会搜索时(和之前)单独处理和保存用户首选项。

相关问题