立即使用React渲染来自fetch的数据。

huangapple go评论107阅读模式
英文:

Immediately render data from fetch with React

问题

我有麻烦从fetch请求中渲染数据。我有一个getUser函数,调用useState(setUsers),我想要将该状态映射到渲染我获取的数据的列表。

显然它不起作用,我不知道是否是因为当我在返回中调用:

{
    users.map((user,index) => {
         <option key={index}>{user.username}</option>
    })
}

时,用户的状态尚未更新。

以下是代码:

export default function NewChannel() {

    let {authToken, user, logout} = useContext(AuthContext)
    let [users, setUsers] = useState([])

    useEffect(
        ()=>{
            let getUsers = async () => {
                console.log(user)
                let response = await fetch(`http://127.0.0.1:8000/user/user`, {
                    method: "GET",
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + String(authToken.access)
                    },
                })
                let data = await response.json()
                if(response.status === 200){
                    setUsers(data)
                }else{
                  alert('You have been logged out')
                  logout()
                }
              }
              getUsers()
              console.log('users',users)
        }, []
    )

    return (
        <div>
            <div className='new-channel-form'>
                <select>
                    {
                        users.map((user,index) => {
                            <option key={index}>{user.username}</option>
                        })
                    }
                </select>
                <input className="submit-button" type="submit"/>
            </div>
        </div>

    )
}

useEffect 结束时的 console.log 实际上记录了获取的数据。

英文:

I'm having troubles rendering data from a fetch request. I have a getUser function that calls useState(setUsers) and I would like to map that state to render a list of the data I've fetched.

Obviously it doesn't work and I don't if it's because when I call

{
    users.map((user,index) =&gt; {
         &lt;option key={index}&gt;{user.username}&lt;/option&gt;
    })
}

in the return the state of users has not been updated yet.

Here's the code:

export default function NewChannel() {

    let {authToken, user, logout} = useContext(AuthContext)
    let [users, setUsers] = useState([])

    useEffect(
        ()=&gt;{

            let getUsers = async () =&gt; {
                console.log(user)
                let response = await fetch(`http://127.0.0.1:8000/user/user`, {
                    method: &quot;GET&quot;,
                    headers: {
                        &#39;Content-Type&#39;: &#39;application/json&#39;,
                        &#39;Authorization&#39;: &#39;Bearer &#39; + String(authToken.access)
                    },
                })
                let data = await response.json()
                if(response.status === 200){
                    setUsers(data)
                }else{
                  alert(&#39;You have been logged out&#39;)
                  logout()
                }
              }
              getUsers()
              console.log(&#39;users&#39;,users)
        }, []
    )

    return (
        &lt;div&gt;
            &lt;div className=&#39;new-channel-form&#39;&gt;
                &lt;select&gt;
                    {
                        users.map((user,index) =&gt; {
                            &lt;option key={index}&gt;{user.username}&lt;/option&gt;
                        })
                    }
                &lt;/select&gt;
                &lt;input className=&quot;submit-button&quot; type=&quot;submit&quot;/&gt;
            &lt;/div&gt;
        &lt;/div&gt;

    )
}

The console.log the end of useEffect actually log the fetched data

答案1

得分: 1

我能够用以下方式解决这个问题:

users.map((user, index) => {
  return <option key={index}>{user.username}</option>
})

或者

users.map((user, index) => (
  <option key={index}>{user.username}</option>
))
英文:

I was able to solve this problem with

users.map((user,index) =&gt; {
  return &lt;option key={index}&gt;{user.username}&lt;/option&gt;
})

or

users.map((user,index) =&gt; (
  &lt;option key={index}&gt;{user.username}&lt;/option&gt;
))

huangapple
  • 本文由 发表于 2023年3月4日 03:13:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定