[英]how to use react fetch() with useEffect hook and map the fetched data
Trying to fetch api data on frontend using useEffect hook,尝试使用 useEffect 挂钩在前端获取 api 数据,
i am able console log the data but unable to map it somehow我能够控制台记录数据,但无法以某种方式 map
new to react新反应
function SlugBook() {
// let {slug} = useParams(),
const [state, setState] = useState([])
useEffect(() => {
fetch("http://127.0.0.1:8000/app/reviews/",{CSRF_TOKEN....}
)
.then(response => response.json())
.then(data => console.log(data)) -->works fine
.then(data => setState(data)); --> not sure
})
return (
<p>
{state.map( d => (<li>{d}</li>))} ---> error code ()
</p>
)
}
export default SlugBook
Two problems:两个问题:
then
like so:你需要在第二个里面设置你的 state then
像这样: useEffect(() => {
fetch("http://127.0.0.1:8000/app/reviews/",{
credentials: 'include',
method: 'GET',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': CSRF_TOKEN
}})
.then(response => response.json())
.then(data => setState(data))
})
useRef
or else you will get infinite re-renders.您需要在useRef
中使用依赖数组,否则您将获得无限的重新渲染。 So change it to:所以改成: useEffect(() => {
fetch("http://127.0.0.1:8000/app/reviews/",{
credentials: 'include',
method: 'GET',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': CSRF_TOKEN
}})
.then(response => response.json())
.then(data => console.log(data)) -->works fine
.then(data => setState(data)); --> not sure
}, [])
Setting the dependancy array to an empty array []
will ensure that your useEffect
only runs your fetch
once on first render.将依赖数组设置为空数组[]
将确保您的useEffect
仅在第一次渲染时运行一次fetch
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.