繁体   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