的按钮调用getLocation
当我主持我的响应时,它就在那里。但是,当我尝试通过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
})
};//通过onclick
您的代码工作正常,但是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>