首页 > 解决方案 > 如何在这些代码中执行正确的 useState?

问题描述

我的渲染有问题,所以我被告知将我使用的表设置为状态,以便数据可以正确更新。

我正在使用的表:

<ScrollView horizontal={true} style={{ marginTop: 20 }}>
  <View>
    <Table borderStyle={{ borderWidth: 1, borderColor: '#C1C0B9' }}>
      <Row
        data={this.state.tableHead}
        widthArr={this.state.widthArr}
        style={styles.header}
        textStyle={styles.text}
      />
    </Table>
    <ScrollView style={styles.dataWrapper}>
      <Table borderStyle={{ borderWidth: 1, borderColor: '#C1C0B9' }}>
        {this.state.tableData.map((rowData, index) => (
          <Row
            key={index}
            data={rowData}
            widthArr={this.state.widthArr}
            style={[styles.row, index % 2 && { backgroundColor: '#F7F6E7' }]}
            textStyle={styles.text}
          />
        ))
        //this.state.myState
        }
      </Table>
    </ScrollView>
  </View>
</ScrollView>

它正在工作render(),我尝试setState onPress选择激活它,我做了类似的事情:

updateState = () =>
  this.setState({
    myState: this.state.tableData.map((rowData, index) => (
      <Row
        key={index}
        data={rowData}
        widthArr={this.state.widthArr}
        style={[styles.row, index % 2 && { backgroundColor: '#F7F6E7' }]}
        textStyle={styles.text}
      />
    )),
  })

但不能让它工作。

标签: reactjsreact-native

解决方案


添加一个toggle状态。此状态将在每个onPress事件上发生变化。

(对于下面的示例,我正在使用onClick

const {useState} = React;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      toggle: false,
    };
    this.data = [1, 2, 3, 4];
  }

  render() {
    return (
      <div>
        <button onClick = {
          () => this.setState({ toggle: !this.state.toggle })
        }>
          {this.state.toggle ? 'hide' : 'show'}
        </button>
        {this.state.toggle ? this.data.map(d => (
          <div>{d}</div>
        )) : null}
      </div>
    );
  }
}

ReactDOM.render(
  <App /> ,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>


推荐阅读