英文:
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) => {
<option key={index}>{user.username}</option>
})
}
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(
()=>{
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>
)
}
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) => {
return <option key={index}>{user.username}</option>
})
or
users.map((user,index) => (
<option key={index}>{user.username}</option>
))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论