反应setState不重新渲染与等待的响应

时间:2020-04-08 12:03:54

标签: javascript reactjs async-await jsx

我正在尝试使用从API获取的数据来呈现组件的内容。

API成功返回数据并更新状态,如控制台输出中所示,记录在渲染器上,并通过比较componentDidUpdate()中的prevState和newState进行记录。

但是,新状态未在组件中呈现,为什么会这样?

如果我转到另一个页面路线,例如,内容会呈现。 '/',然后返回到'/ table',但是刷新页面时并非如此。

感谢任何帮助

export default class Table extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
    };
  }

  componentDidMount() {
    this.getTableRows();
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('Component did update. Prev: ', prevState, 'New: ', this.state);
  }

  getTableRows = async () => {
    try {
      const response = await fetchData();
      this.setState({
        data: response,
      });
    } catch (err) {
      console.log(err);
    }
  };

  render() {
    console.log('RENDER - props:', this.props, 'state:', this.state);
    return (
        <Container>
          <Table.Body>
            {this.state.data.map(item => {
              return (
                <TableRow
                  key={item.key}
                  response={item.response}
                  approved={item.approved}
                />
              );
            })}
          </Table.Body>
        </Container>

更新:其他上下文

这是状态数据的一个示例:

[
  {
    "key": "recBIW8drmVpC8sNT",
    "response": "Example",
    "approved": true,
    "date": "2020-04-02T03:30:00.000Z"
  },
  {
    "key": "recWZtUAHf4Z78lP2",
    "response": "Example",
    "approved": true,
    "date": "2020-04-03T20:30:00.000Z"
  },
  {
    "key": "recch8GoP59PyftxX",
    "response": "Example",
    "approved": true,
    "date": "2020-03-31T23:00:00.000Z"
  },
  {
    "key": "recg8uRL6RSKroCjZ",
    "response": "Example",
    "approved": true,
    "date": "2020-04-04T22:00:00.000Z"
  },
  {
    "key": "recimzyYWbVf1c7WC",
    "response": "Example",
    "approved": true,
    "date": "2020-04-06T01:00:00.000Z"
  }
]

这是我在getData()中构造返回对象的方式:

let data = [];

fetchAirtableData = async () => {
  base('Responses')
    .select()
    .eachPage(
      function page(records, fetchNextPage) {
        // This function (`page`) will get called for each page of records.

        records.forEach(function(record) {
          let key = record.getId();
          let response = record.get('Response');
          let approved = record.get('Approved');
          let date = record.get('Date Submitted');

          data.push({ key, response, approved, date });
        });

        fetchNextPage();
      },
      (cb = err => {
        if (err) {
          console.error(err);
          return;
        }
      }),
    );

  return data;
};

Here's the output in the console (image)

0 个答案:

没有答案