[英]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>
)
我无法执行您的代码,因为更改太多而无法尝试,但我相信问题来自生命周期。
让我们逐步分析应用程序:
除非您有数据,否则请确保不要渲染模态框。 这样,在第一次渲染时,状态将被正确初始化。
像这样:
{showModalEditCommunity && (<ModalEditCommunity
handleCloseModal={handleCloseModalEditCommunity}
showModal={showModalEditCommunity}
community={community}
/>)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.