![](/img/trans.png)
[英]Saving api response to State using useState and Axios (React JS)
[英]React useState Not Updating on Axios Response
在服務器成功響應后,我正在嘗試更新點擊喜歡的次數,並且一切正常。 但是,喜歡的數量沒有更新,我需要刷新頁面才能看到元素上的更新值。
function UserPage() {
const [posts, setPosts] = useState([])
let {authTokens, user} = useContext(AuthContext)
useEffect (()=>{
const getData = async () => {
const{data: ServerResponse} = await axios.get('http://127.0.0.1:8000/api/tweets/');
setPosts(ServerResponse)
}
getData();
}, [])
const handleLike = (id)=>{
let posts_list = posts
const post_indx = posts_list.findIndex((post=> post.id==id))
posts_list[post_indx].likes++
axios({
method: 'post',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + String(authTokens.access)
},
url: 'http://127.0.0.1:8000/api/tweets/action/',
data: {
id: id,
action:"like"
}
}).then(function(response){
setPosts(posts_list)
}
)
}
const handleDelete=(id)=>{
// console.log("hi")
}
return (
<div>
<NavBar className='navbar' />
{user && <p>Hello {user.username}</p>}
{
posts.map(post=>(
<SingleTweet onDelete={() => handleDelete(post.id)} numLikes={post.likes} onLike={() => handleLike(post.id)} id={post.id} content={post.content} />
))
}
</div>
);
}
另外,SingleTweet 組件如下:
class SingleTweet extends Component {
state = { }
render() {
return (
<div className='border'>
<div className='id-ret'>
<h3>{this.props.id}</h3>
<button onClick={this.props.onLike} type="button" className="btn btn-outline-primary me-1">Retweet</button>
</div>
<p>{this.props.content}</p>
<div className='tweet-buttons'>
<div>
<button onClick={this.props.onLike} type="button" className="btn btn-primary me-1">{this.props.numLikes} Likes</button>
<button onClick={this.props.onLike} type="button" className="btn btn-outline-primary me-1">Unlike</button>
</div>
<button onClick={this.props.onDelete} type="button" class="btn btn-danger me-2">Delete</button>
</div>
</div>
);
}
}
任何建議將不勝感激
你的 state 是一個數組。 由於 object 引用保持不變,React 不會更新 state 認為沒有任何變化。
它在頁面重新加載后顯示的原因是因為您在后端更新了相同內容,並且后端在加載時返回正確的數據,即新的 object。
解決問題的一種方法是執行以下操作:
setPosts([...posts_list])
這將創建一個具有相同數據的新數組,從而導致引用發生變化。 一旦引用發生變化,React 就會知道更新 state。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.