您如何从子组件更改父组件的状态?

时间:2020-05-08 06:51:25

标签: javascript reactjs react-native

我要做什么

在我的第一个组件中,我得到状态为2的项目并将其放入复选框。

在第二个组件中,我将商品的状态更改为3。

在第三个组件中更改状态后,将打开第三个组件。

“模式”关闭时,导航返回到第一个组件。

问题是我更改状态的项目仍在第一个组件中。

它们的状态为3,因此它们不应位于第一个组件中。

在这种情况下,您该如何解决?

它看起来像componentDidUpdate在这里不起作用。

如果您能给我任何建议,我将不胜感激。

当前代码

第一部分

export default class fist extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      checkedItems: [],
    };
  }

  onUpdate = (item) => {
    this.setState((previous) => {
      const { checkedItems } = previous;
      const index = checkedItems.indexOf(item);
      if (index === -1) {
        checkedItems.push(item);
      } else {
        checkedItems.splice(index, 1);
      }
      return { checkedItems };
    });
  };

  async componentDidMount() {
    const items = db.itemsCollection
      .where('status', '==', 2)
      .get();
    this.setState({ items });
  }

  render() {
    const { items, checkedItems } = this.state;
    return (
      <Container>
        <View style={styles.list_asset}>
          {items.map((item) => (
            <View style={styles.article_asset} key={item.id}>
              <Text style={styles.phrase}>{item.name}</Text>
              <View style={styles.area_price}>
                <CheckBox
                  style={styles.check}
                  checked={!!checkedItems.find((obj) => obj == item)}
                  onPress={() => this.onUpdate(item)}
                />
              </View>
            </View>
          ))}
        </View>
      </Container>
    );
  }
}

第二部分

updateItemsStatus = (id) => {
    this.itemsCollection.doc(id).update({
      status: 3,
      updated_at: new Date(),
    });
    return true;
  }

第三部分

<TouchableOpacity
  onPress={() => {this.props.navigation.navigate('first component')}}
>
  <Text>Close Modal</Text>
</TouchableOpacity>

1 个答案:

答案 0 :(得分:0)

据我了解,您的问题是关闭模态后不会刷新您的数据。

这是因为您在一次触发的ComponentDidmount()中获取了数据,然后直接更新了数据库。

在第二个组件中,您可以从父级传递一个方法来更新您的状态。这是一个通用示例:

class App extends React.Component {

  state = {...items};

  updateState = (newStatus) => {
    this.setState(prevState => ({...prevState, status:newStatus}));
    // or get data again from your db (careful about async)
  };
  render() {
    return (
      <Child updateState={updateState} />
    )
  }

}

class Child  extends React.Component {
  render(){
    return <TouchableOpacity onPress={() => this.props.updateState(3)}>Touch me daddy</TouchableOpacity>
  }
}