react-native-table-component使用状态来呈现表数据

时间:2019-02-26 00:37:32

标签: javascript react-native state

我正在使用react-native-table-component来在react-native中呈现一个表,该表需要显示从服务器接收到的数据,因此它经常更改。

示例仅显示硬编码到每一行的数据,我需要在将新数据推送到客户端后立即对其进行更新。

代码示例

export default class ExampleTwo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableHead: ['', 'Head1', 'Head2', 'Head3'],
      tableTitle: ['Title', 'Title2', 'Title3', 'Title4'],
      tableData: [
        ['1', '2', '3'],  //data I need to be dynamic
        ['a', 'b', 'c'],
        ['1', '2', '3'],
        ['a', 'b', 'c']
      ]
    }
  }

  render() {
    const state = this.state;
    return (
      <View style={styles.container}>
        <Table>
          <Row data={state.tableHead} flexArr={[1, 2, 1, 1]} style={styles.head} textStyle={styles.text}/>
          <TableWrapper style={styles.wrapper}>
            <Col data={state.tableTitle} style={styles.title} heightArr={[28,28]} textStyle={styles.text}/>
            <Rows data={state.tableData} flexArr={[2, 1, 1]} style={styles.row} textStyle={styles.text}/>
          </TableWrapper>
        </Table>
      </View>
    )
  }

}

react-native-table-component中的代码

{data.map((item, i) => { const height = heightArr && heightArr[i]; return ( <Row key={i} data={item} widthArr={widthArr} height={height} flexArr={flexArr} style={style} textStyle={textStyle} {...props} /> ); })}

2 个答案:

答案 0 :(得分:0)

有很多方法可以做到,我假设您必须在一定间隔后轮询服务器并更新屏幕,您可能会这样:

在特定时间间隔后进行轮询

        constructor(props) {
           super(props);
           this.state = {
           tableHead: ['', 'Head1', 'Head2', 'Head3'],
           tableTitle: ['Title', 'Title2', 'Title3', 'Title4'],
           tableData: [ ],
          keepPolling: true
        }

        componentWillMount()
        {
          pollAfter(60 * 1000, ()=>{
            // get your data from the server here 
          }).then((response)=>{
           // and set state here like this
           this.setState({
             tableData : response
             });
          })
        }

        pollAfter(intervalDuration, fn) {
            const asyncTimeout = () => setTimeout(() => {
                this.pollAfter(intervalDuration, fn);
            }, intervalDuration);
            const assignNextInterval = () => {
                if (!this.keepPolling) {
                    this.stopPolling();
                    return;
                }
                this.interval = asyncTimeout();
            };

            Promise.resolve(promise)
            .then(assignNextInterval)
            .catch(assignNextInterval);
        }

答案 1 :(得分:0)

这是我解决的方式。

状态变量:

this.state = {
    data: []
}

另一个变量widthArr

const widthArr = [150, 150, 200, 100, 150]; // same length as your columns

从api获取数据后,使用map将其转换为字符串:

    const { data } = await axios.get(url, { headers: Api.headers }).catch((error) => {
      this.showError(error.message);
    });
    console.log(data.items.data);
    const records: [] = data.items.data;
    const rows = [];
    records.forEach((item) => {
      rows.push([
        item.name || 'Item',
        item.category,
        item.vendor_name,
        item.quantity,
        `$${item.price}`
      ])
    })
    this.setState({ 
      data: rows,  
      loading: false 
    });

现在您可以在下表中使用它了:

<Table
  borderStyle={{ borderColor: Colors.border }}
  style={{ borderRadius: 10 }}
  textStyle={{ fontSize: 16, fontFamily: 'nunito' }}
>
  <Row
    data={["Product","Type", "Vendor", "Total Qty", "Total Price"]}
    style={{ flexWrap: 'wrap' }}
    textStyle={styles.headText}
    widthArr={widthArr}
  />
  <Rows
    data={this.state.data}
    style={{ flexWrap: 'wrap' }}
    textStyle={styles.rowText}
    widthArr={widthArr}
  />
</Table>