【发布时间】:2020-01-24 14:00:49
【问题描述】:
我有一个 Home 组件,它从 API 获取数据并将数据发送到我的模态组件。在这个模态组件中,我将使用这些数据来填写表格。
问题是,在我的模式中,我可以 console.log 来自我的 Home 组件的对象,但我的输入没有获取数据,它们是空的。
就像我的 Home 组件被渲染时一样,即使我没有点击打开我的模态, 我的 Home 组件正在将空对象发送到我的 Modal 组件。
我对 React 还很陌生,所以任何提示都将不胜感激。
我的 Home 组件(由于代码太大而进行了一些编辑):
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>
)
【问题讨论】:
-
您已将社区对象作为属性传递给 ModalEditCommunity 组件。所以它应该可以通过你的 ModalEditCommunity 组件中的 this.props.community 访问!
-
如果您希望我们帮助您,请尝试摆脱其他组件并提供仅包含两个组件的代码:Home 和 Modal。
-
嘿@Kingalione 功能组件不能使用“this”
-
@Meziane 还有哪些其他组件? Home和Modal组件代码已经有了,不知道你的意思
-
您的问题已解决:您已接受答案。非常好。我的意思是让代码尽可能短。
标签: javascript reactjs