SetState не принимает число - PullRequest
0 голосов
/ 29 апреля 2018

Я новичок, чтобы реагировать, и я не понимаю, почему я получаю следующую ошибку при установке состояния для componentDidMount. Я провел исследование подобных ошибок, и я понимаю, что реакция хочет получить число, а не обещание. Тем не менее, я почти уверен, что разрешу число, написав .then(res => res.json().then(data => data). Поэтому я не могу понять, откуда ошибка.

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    in p (created by Info)
    in div (created by Info)
    in Info

Это функция, которую я использую для получения числа:

const get_eth = wallet =>
  fetch(
    `https://api.etherscan.io/api?module=account&action=balance&address=${wallet}&tag=latest`
  )
    .then(res =>
      res.json().then(data => data["result"] / 10 ** 18)
    )
    .catch(err => console.log(err));

И это setState:

  componentDidMount() {
    this.setState({eth_q: get_eth("0x0975ca9f986eee35f5cbba2d672ad9bc8d2a0844")})
  }

1 Ответ

0 голосов
/ 29 апреля 2018

Я думаю, что вы хотите:

const get_eth = wallet =>
  fetch(API)
    .then(res => res.json())
    .then(data => data["result"] / 10 ** 18)
    .catch(err => console.log(err));

То есть, вы приковываете .then() к .json() вместо fetch().

Тогда в вашем componentDidMount():

componentDidMount() {
  get_eth('0x0975ca9f986eee35f5cbba2d672ad9bc8d2a0844').then(res => {
    this.setState({ eth_q: res });
  });
}
...