Reactjs 如何将react fetch()与useEffect挂钩一起使用并映射所获取的数据

Reactjs 如何将react fetch()与useEffect挂钩一起使用并映射所获取的数据,reactjs,react-hooks,frontend,fetch,Reactjs,React Hooks,Frontend,Fetch,尝试使用useEffect钩子在前端获取api数据, 我可以用控制台记录数据,但无法以某种方式映射数据 新反应 函数SlugBook(){ //设{slug}=useParams(), const[state,setState]=useState([]) useffect(()=>{ 取回(“http://127.0.0.1:8000/app/reviews/“,{CSRF_令牌…” ) .then(response=>response.json()) .then(data=>console.

尝试使用useEffect钩子在前端获取api数据,

我可以用控制台记录数据,但无法以某种方式映射数据

新反应

函数SlugBook(){
//设{slug}=useParams(),
const[state,setState]=useState([])
useffect(()=>{
取回(“http://127.0.0.1:8000/app/reviews/“,{CSRF_令牌…”
)
.then(response=>response.json())
.then(data=>console.log(data))-->工作正常
.然后(数据=>设置状态(数据));-->不确定
})
返回(

{state.map(d=>(
  • {d}
  • )}-->错误代码()

    ) } 导出默认SlugBook
    两个问题:

  • 您需要在第二个
    中设置您的状态,然后像这样设置:
  • 您需要在
    useRef
    中使用依赖项数组,否则将得到无限重渲染。因此,将其更改为:

  • 将依赖性数组设置为空数组
    []
    将确保您的
    useffect
    仅在第一次渲染时运行
    fetch
    一次。

    data=>console.log(data)
    是一个无效返回,因此您将
    未定义的
    返回到下一个可执行的数组,即
    设置状态(未定义)
    。您的
    useffect
    钩子缺少依赖项,因此任何状态更新都将触发渲染循环。它将提供最小化的响应error@VishalGupta不确定缩小的反应错误是什么。
    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
    
        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))
        })
    
        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
    
            
        }, [])