简体   繁体   English

react setState Hook 并不总是更新 object

[英]react setState Hook doesn't always update object

Hi I am using a setState Hook with useContext to to update/overwrite a Json object.嗨,我正在使用带有 useContext 的 setState Hook 来更新/覆盖 Json object。 setState is used in a GET API call and the data returned is used to update my state, the state will update initially then will not update again. setState 用于 GET API 调用,返回的数据用于更新我的 state,state 最初会更新,然后不会再次更新。

The initial state looks like so: This is also the shape of the data that will be returned from the database.最初的 state 如下所示: 这也是将从数据库返回的数据的形状。

export const NewsArticlesInitialState = {
  id: null,
  title: '',
  heroImage: '',
  summaryImage: '',
  thumbnail: '',
  summary: '',
  bodyHeading: '',
  body: '',
  steps: [],
  tags: [],
  date: null,
} as NewsArticlesJson

This is where the setState is called, it does update but if called again after the first time it updates infrequently, I know the function is being called as I have run a console.log next to the setNewsArticlesJson() hook.这是调用 setState 的地方,它确实会更新,但如果在第一次不经常更新后再次调用,我知道 function 正在被调用,因为我在 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 }
}

Where the component is called:调用组件的位置:

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>
  )
}

I have identified that that reason for my error is with a library called react-quill using the output of this setState as I am setting the data its is causing a rerender on the onchange function when it should not, I am currently unaware how to fix this issue.我已经确定我的错误的原因是一个名为 react-quill 的库使用这个 setState 的 output 因为我正在设置数据,它导致在 onchange function 上重新呈现它不应该时,我目前不知道如何修复这个问题。 but have identified the cause但已查明原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM