导航到主页后,React Native不更新状态

时间:2020-02-13 22:59:46

标签: javascript reactjs react-native

我创建一个与所有页面(组件)共享的页脚组件。它具有更新所选属性并返回到首页的选项。

class FooterComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      CurrentPropertyID: null
    };
  }

  componentDidMount() {
    AsyncStorage.getItem('userID')
      .then((value) => {
        const userID = JSON.parse(value);
        this.props.getProperties(userID); // Here I get list of properties and set in this.props.properties
    });

    // Get the current selected propertyID
    AsyncStorage.getItem('CurrentPropertyID')
      .then((value) => {
        const propID = JSON.parse(value);
        this.setState({
          CurrentPropertyID: propID.toString()
        });
    });
  }

  changeProperty = async (data) => {
    // Set the current propertyID in my session
    await AsyncStorage.setItem('CurrentPropertyID', data.toString());
    // Update the state
    await this.setState({ CurrentPropertyID: data.toString() });
    // Navigate back to the Home component
    NavigationService.navigate('Home');
  }

  render() {
    const  { CurrentPropertyID } = this.state; 

    return (
      <Footer style={styles.footer}>
        <FooterTab style={styles.footerStyle}>
          <Item picker>
              <Picker
                mode="dropdown"
                iosHeader="Select Property"
                placeholder="Property"
                iosIcon={<Icon name="arrow-down" />}
                style={{ width: undefined }}
                selectedValue={CurrentPropertyID}
                onValueChange={this.changeProperty.bind(this)}
              >
              {Object.keys(this.props.properties).map((key) => {
                  return (
                    <Picker.Item
                      label={this.props.properties[key]}
                      value={key}
                      key={key}
                    />
                  );
              })}
              </Picker>
          </Item>
        </FooterTab>
      </Footer>
    );
  }
}
...

如果我在home组件中,则可以完美运行。但是,如果我在另一个组件中并被重定向回home组件,则所选属性不会更新。它显示了先前的属性。看来FooterComp没有被更新。

顺便说一句,我叫FooterComp,只是将其包括在其他组件中:

import FooterComp from './Footer';
...
...
<FooterComp />
...
...

我在做什么错了?

0 个答案:

没有答案