簡體   English   中英

ReactJS - 獲取數據並發送到另一個組件的正確方法

[英]ReactJS - proper way to fetch data and send to another component

我有一個 Home 組件,它從 API 獲取數據並將數據發送到我的模態組件。 在這個模態組件中,我將使用這些數據來填寫表格。

問題是,在我的模式中,我可以 console.log 來自我的 Home 組件的對象,但我的輸入沒有獲取數據,它們是空的。

就像當我的 Home 組件被渲染時,即使我沒有點擊打開我的模式,我的 Home 組件也會將空對象發送到我的 Modal 組件。

我是 React 的新手,所以任何提示都將不勝感激。

我的主頁組件(做了一些編輯,因為代碼太大):

export default function Home() {
  const token = useSelector(state => state.auth.token)

  const [community, setCommunity] = useState([])
  const [showModalEditCommunity, setShowModalEditCommunity] = useState(false)

  function handleCloseModalEditCommunity() {
    setShowModalEditCommunity(false)
  }

  function handleShowModalEditCommunity() {
    setShowModalEditCommunity(true)
  }

  // fetching data and then saving the response into my community state
  useEffect(() => {
    const getCommunityInformations = async () => {
      const options = {
        headers: {
          Authorization: token,
        }
      }
      try {
        const result = await axios(
          "https://sandbox.herokuapp.com/community/38", options
        )
        setCommunityProducts(result.data)

      } catch (error) {
        toast.error('Failed to fetch data from the server')
      }
    }
    getCommunityInformations()
  }, [])

  return (
    <Container fluid as="section">
      <Row>
        <Col md={8}>
          <S.InviteSponsorSection>
            <div className="d-flex flex-column">
              <p className="title">Your community can do much more!</p>  
            </div>
             <ProfileButton
                backgroundColor="#27b8fe"
                image="/icons/edit.png"
                onClick={handleShowModalEditCommunity}
              />
            // my modal and the data I'm sending
            <ModalEditCommunity
              handleCloseModal={handleCloseModalEditCommunity}
              showModal={showModalEditCommunity}
              community={community}
            />
          </S.InviteSponsorSection>
        </Col>
      </Row>
    </Container>
  )
}

我的模態組件

export default function ModalEditCommunity({ handleCloseModal, showModal, community }) {

  // first two console.log gives me an empty array, because I'm in my Home component, but when
  // I click to open the modal, this console.log show the exact object that is coming from my 
  // Home component, but all the inputs are empty

  console.log('community', community)

  const [name, setName] = useState(community.name)
  const [description, setDescription] = useState(community.description)
  const [facebookPage, setFacebookPage] = useState(community.facebook)

  return (
   <form onSubmit={handleSubmit(onSubmit)}>
      <TextField
         variant="outlined"
         fullWidth={true}
         name="name"
         type="text"
         value={name}
         onChange={e => setName(e.target.value)}
       />
       <TextField
         fullWidth={true}
         variant="outlined"
         name="description"
         multiline
         rows="2"
         value={description}
         onChange={e => setDescription(e.target.value)}
       />
       <TextField
         variant="outlined"
         fullWidth={true}
         name="facebookPage"
         type="text"
         value={facebookPage}
         onChange={e => setFacebookPage(e.target.value)}
        />
   </form>
  )

我無法執行您的代碼,因為更改太多而無法嘗試,但我相信問題來自生命周期。

讓我們逐步分析應用程序:

  1. 加載主頁,初始化狀態,觸發 XHR 調用,進行首次渲染。 在這第一個渲染中,ModalEditCommunity 已經被渲染了,但是 props 是空的。
  2. 在 ModalEditCommunity 中,首先會觸發渲染。 該組件使用空值初始化其狀態,因為 XHR 調用尚未完成。
  3. XHR 調用返回。 Home 組件更新其狀態。 這會觸發新的渲染。 結構保持不變,但道具發生變化。
  4. 在 ModalEditCommunity 中,狀態已經被初始化。 它的值是在渲染部分使用的值。 所以它不會改變。

如何解決

除非您有數據,否則請確保不要渲染模態框。 這樣,在第一次渲染時,狀態將被正確初始化。

像這樣:

{showModalEditCommunity && (<ModalEditCommunity
     handleCloseModal={handleCloseModalEditCommunity}
     showModal={showModalEditCommunity}
     community={community}
/>)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM