为何在提取数据后useState不起作用

时间:2019-03-20 20:54:29

标签: reactjs react-hooks

当我console.log来自api的响应时,它就在那里。但是,当我尝试通过usestate挂钩设置状态时,它不会更新状态。

const [data, setData] = useState([])

  const getLocation = () => {
axios
  .get(
    `https://myrequest=${
      process.env.REACT_APP_GOOGLE
    }&address=${location}`
  )
  .then(response => {
    console.log(response) //response is present
    setData(response)
    console.log(data)// data didn't update,empty array
  })

}; // getLocation由带有onClick的按钮

调用

1 个答案:

答案 0 :(得分:1)

您的代码正在运行,但是data不会通过调用setData来同步更新,并且data仍然是对旧数组的引用。

尝试呈现data,您会看到它正确更新。

示例

const { useState } = React;

function getData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(['foo', 'bar'])
    }, 1000)
  })
}

function App() {
  const [data, setData] = useState([])

  function getLocation() {
    getData().then(response => {
      setData(response)
      console.log(data)
    })
  }

  return (
    <div>
      {data.map(item => (
        <div key={item}>{item}</div>
      ))}
      <button onClick={getLocation}>Load location</button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

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