尝试在 React Native 中刷新组件(使用列表和 Lists.push)

Trying to Refresh a Component in React Native (with Lists and Lists.push)

所以我已经在这个问题上摸不着头脑了很长一段时间,但不确定如何进行。我是 RN 的新手(2 周)。我正在构建这个列表应用程序。我正在使用 AsyncStorage 将两个项目设置为 True。

然后我检查它们是否为真,如果为真,则将一个项目推送到列表数组。如果我更改 AsyncStorage 值,我想刷新屏幕,这样我就可以清除列表并重新推送正确的项目。

export default class CheckOut extends React.Component {

  constructor() {
    super()
    this.state = {
      refreshing: false,
      checked: false,
      one: false,
      two: false,
      list: []
    }
  }

  static navigationOptions = {
    header: null,
    };

  componentDidMount() {
    this.setState({"refreshing" : "false"});
    AsyncStorage.getItem("one").then((value) => {
        this.setState({"one" : value});
        if (this.state.one === "true"){
          this.state.list.push({
            name: 'Butter',
            avatar_url: 'https://i.imgur.com/IueK52c.png',
            checkbox: 1,
            key: 1,
          })
        }
     });
    AsyncStorage.getItem("two").then((value) => {
        this.setState({"two" : value});
        if (this.state.two === "true"){
          this.state.list.push({
            name: 'Butter Milk',
            avatar_url: 'https://i.imgur.com/9SENqe3.png',
            checkbox: 2,
            key: 2,
          })
        }
    });
  }
  _onRefresh = () => {
    this.setState({"refreshing" : "true"});
  }
  render() {
    return(
      <View containerStyle = {{backgroundColor: '#FFF'}}>

      <ScrollView containerStyle = {{backgroundColor: '#FFF'}}>

        <View>
        <ScrollView>
        <List containerStyle = {{
          flex: 1,
          marginTop: 0,
          borderTopWidth: 0,
          paddingBottom: 10
          }}>
          {this.state.list.map((l) => (
            <ListItem containerStyle = {{ height: 80, paddingTop: 15, borderTopWidth:0, borderBottomWidth: 0.25}}
              title={l.name}

            />
          ))
        }
        </List>
        </ScrollView>
        </View>
      </ScrollView>
      <TouchableOpacity
    onPress={() => this._onRefresh}
      >
        <Icon
      name={"refresh"}
      size={30}
      type='entypo'
      color="#FFF"
       />
      </TouchableOpacity>
      </View>
    )
  }
}

抱歉格式不正确。但是是的,刷新按钮应该在可触摸的不透明度内。我试过更改状态和强制更新,但它们没有用。我想刷新组件和列表,然后在按下刷新按钮时再次推送到列表。

也许先尝试一些在线教程,但是...

您的列表应该在您的 App state.

范围内

因此,参考 this.state.list - 添加到列表时,您应该使用 setState

这里有一些有用的链接,用于添加到状态数组:

Correct modification of state arrays in ReactJS

查看生命周期和状态的 React 文档:

https://reactjs.org/docs/state-and-lifecycle.html