嗨,我正在使用setState挂钩和useContext来更新/覆盖Json对象。在GET调用中使用setState,返回的数据用于更新我的状态,状态将最初更新,然后不再更新。
初始状态如下所示:这也是将从数据库返回的数据的形状。
export const NewsArticlesInitialState = {
id: null,
title: '',
heroImage: '',
summaryImage: '',
thumbnail: '',
summary: '',
bodyHeading: '',
body: '',
steps: [],
tags: [],
date: null,
} as NewsArticlesJson这就是调用setState的地方,它确实会更新,但是如果在第一次更新之后再次调用,我知道函数正在被调用,因为我已经在setNewsArticlesJson()钩子旁边运行了一个console.log。
export const GetArticles = () => {
const accessToken = useContext(AccessTokenContext)
const setNewsArticlesJson = useContext(NewsArticlesSetContext)
const getArticle = async (id: number | null) => {
try {
axios
.get(`${NEWS_ARTICLE_ENDPOINT}/${id}`, {
headers: {
Authorization: 'Bearer ' + accessToken,
},
})
.then((res) => {
setNewsArticlesJson({ ...res.data })
})
} catch (err) {
console.log(err)
}
}
return { getArticle }
},其中调用组件:
export const ArticleEdit = () => {
const newsArticleJson = useContext(NewsArticlesContext)
const setNewsArticlesJson = useContext(NewsArticlesSetContext)
const newsArticleList = useContext(NewsArticlesEditListContext)
const { getArticles, getArticle } = GetArticles()
const [editArticle, setEditArticle] = useState('New')
const [selectedArticle, setSelectedArticle] = useState(newsArticleJson.title)
const editArticles = (e: string) => {
switch (e) {
case 'New':
setEditArticle('New')
setNewsArticlesJson({ ...NewsArticlesInitialState })
setSelectedArticle(newsArticleList[0]?.title)
break
case 'Edit':
setEditArticle('Edit')
getArticles()
}
}
//funtions that calles the hook causing issues
const selectArticle = (e: any) => {
const filteredArticles = newsArticleList.filter((d) =>
d.title === e ? d : null
)
setSelectedArticle(e)
getArticle(filteredArticles[0].id)
}
return (
<RiskEditContainer>
<RadioGroup
value={editArticle}
onChange={(e) => editArticles(e.target.value)}
>
<FormControlLabel value="New" control={<Radio />} label="New Article" />
<FormControlLabel
value="Edit"
control={<Radio />}
label="Edit Article"
/>
</RadioGroup>
{editArticle === 'Edit' && (
<Select
value={selectedArticle}
onChange={(e) => selectArticle(e.target.value)}
>
{newsArticleList.map((data, idx) => {
return (
<MenuItem key={idx + data.title} value={data.title}>
{data.title}
</MenuItem>
)
})}
</Select>
)}
</RiskEditContainer>
)
}发布于 2021-05-12 12:18:57
我已经确定了导致我错误的原因是一个名为react的库,它使用这个setState的输出,因为我正在设置它的数据,当它不应该改变函数时,它会导致一个重振子,我目前还不知道如何解决这个问题。但是已经确定了原因
https://stackoverflow.com/questions/67499210
复制相似问题