简体   繁体   English

状态更改后反应组件不会重新渲染

[英]react component is not re-rendering after state is changed

export default function RenderPages({storage, setStorage, state, setState}){
  const [pageNum, setPageNum]= useState(0)

  const currentFileId=state.currentFileId
  const currentFolderId= state.currentFolderId

  return (
    <div className="writing">
      {storage[currentFolderId][currentFileId].content.map((page, index)=>
      <div className='textarea'>
        <textarea placeholder='write here' defaultValue={page} id={index} onChange={(e)=>onChange(e, index)} rows={rows} cols={cols}></textarea>
      </div>)}
    </div>
  )
}

I expected that jsx would return renewal result after the state is changed, but it didn't.我预计 jsx 会在状态更改后返回更新结果,但事实并非如此。 I checked that currentFileId and currentFolderId value were changed.我检查了 currentFileId 和 currentFolderId 值是否已更改。 why this happen?为什么会这样?

You should make sure you are not just mutating the state prop.你应该确保你不只是改变state属性。

A new reference should be created for react to know the state prop changed, if you just mutate state it is still the same reference despite some of its properties changed.应该创建一个新的引用,以便做出反应以了解state属性已更改,如果您只是改变state ,尽管它的某些属性已更改,但它仍然是相同的引用。

As an alternative, you could pass the values you are changing instead of the whole object:作为替代方案,您可以传递正在更改的值而不是整个对象:

export default function RenderPages({storage, setStorage, currentFileId, currentFolderId}){
  const [pageNum, setPageNum]= useState(0)

  return (
    <div className="writing">
      {storage[currentFolderId][currentFileId].content.map((page, index)=>
      <div className='textarea'>
        <textarea placeholder='write here' defaultValue={page} id={index} onChange={(e)=>onChange(e, index)} rows={rows} cols={cols}></textarea>
      </div>)}
    </div>
  )
}

it could be that the error is here where you need to return strings with the value of the key inside the literal object, if you can show the state it would help too.可能是错误出现在这里,您需要在文字对象中返回带有键值的字符串,如果您可以显示状态,它也会有所帮助。

let storage = {
     currentFolder:{
        id:12313,
        file:{
          id:1231  
        }
     }
 }


storage['currentFolder']['id'] // output = 12313 

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

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