【发布时间】:2021-03-14 23:55:31
【问题描述】:
我正在使用 Hook 创建一个功能性的 React 组件。在我的组件中,我使用 Axios API 从 REST API 获取数据。这是我的代码,但是问题是当我传递从服务器接收到的数据时,状态变量没有更新。我使用了 useEffect Hook,我使用 axios API 来获取数据。
但是,当我使用此数据设置状态变量时,收到了数据,状态变量返回未定义的错误,不确定我缺少什么。请任何cmets。我注意到setState(data) 不会更新状态变量。但是后来当我检查按钮的单击事件中的状态变量时,我发现状态变量是从获取的数据中更新的。请查看状态变量返回值的点击处理程序中的代码。但是,我希望它在不单击按钮的情况下进行更新。任何意见请。
function TestState()
{
const [count, setCount] = useState(10);
const [state, setState] = useState({
booktitle:"",
Author:"",
Year:1990,
Topic:"",
format:""
})
function Setstatewithdata(data)
{
console.log("state vrb",state, "count",count)
setState(state);
console.log("after state vrb",state, "count",count)
}
useEffect(() =>
{
console.log("useeffect count is ",count,"author",state.author)
axios.get("http://localhost:5000/allbooks")
.then(res => {
console.log("data received "+res.data)
res.data.map(function(currentstate, i){
console.log("data.res"+currentstate.Author)
})
Setstatewithdata(res.data)
} //
)
.catch(err => {
console.log("error has occured"+ err)
})
}, [])
const ClickHandle=() =>
{
console.log("state vrb",state.Author, "count",count)
setCount(count + 1)
console.log(state)
}
return (
<div className="App-header">
<form>
<div>
<h3>Data Received List</h3>
</div>
<h1>Click Counts are {count}</h1>
<button type= "button" onClick={ClickHandle}>Click me{count} </button>
</form>
</div>
);
}
export default TestState
【问题讨论】:
-
只是
setState(data)?因为setState([state, data])没有任何意义。 -
我想得到 url
api真正的测试
标签: reactjs react-hooks react-component