简体   繁体   中英

react component return problem when props are null

export default function RenderPages({storage, setStorage, state, setState}){
  let elRefs= useRef()
  
  if(!storage) return
  if(!state.currentFileId || !state.currentFolderId) return
  
  const content = storage[state.currentFolderId][state.currentFileId].content

  return (
    <div className="writing">
      <input ref={elRefs}/>
      {content.map((page, index)=>
      <div className='textarea'>
        <textarea placeholder='write here' value={page} id={"page"+index} onChange={(e)=>onChange(e, index)} rows={rows} cols={cols}></textarea>
      </div>)}
    </div>
  )
}

There are some props(state, storage) and they are sometimes null value. What I am doing now is checking the values of state and storage, returning blank early if those values are null. If I don't return in advance, the variable "content" get error because it needs state and storage value. Now this is the problem. I want to use "useRef", and if the component return early "elRefs" is assigned null value, so I can't get DOM element. What should I do?

I put your booleans into single function and seperated the renderable part of component. If bool is false, that component is simply not rendered. Of course you can put in there other component which shows error data or loading gif or something like that. Hope this works

 export default function RenderPages({ storage, setStorage, state, setState }) { const elRefs = useRef() const content = storage[state.currentFolderId][state.currentFileId].content // content to render in seperate component const Pages = () => ( <div className="writing"> <input ref={elRefs} /> { content.map((page, index) => <div className='textarea'> <textarea placeholder='write here' value={page} id={"page" + index} onChange={(e) => onChange(e, index)} rows={rows} cols={cols} /> </div> ) } </div> ) // decide to or not to render component const renderable = storage && state.currentFileId && state.currentFolderId return ( <> { renderable? <Pages />: <></> // returns empty component } </> ) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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