[英]How to set initial value using useState hook from Redux store?
I'm trying to make an edit form for my model and set the initial values of the form to the values of the model.我正在尝试为我的 model 制作一个编辑表单,并将表单的初始值设置为 model 的值。 I've tried:
我试过了:
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getPost, destroyPost } from '../../actions/posts'
import { useHistory } from "react-router-dom";
const Edit = ({ match }) => {
const dispatch = useDispatch()
const history = useHistory()
const post = useSelector(state => state.post)
const postId = match.params.id
const handleClick = () => {
dispatch(destroyPost(postId))
history.push("/")
}
const [formData, setFormData] = useState({
title: post.attributes.title,
body: post.attributes.body
})
useEffect(() => {
dispatch(getPost(postId))
}, [])
if (!post) { return <div>Loading...</div>}
const handleSubmit = (e) => {
e.preventDefault()
console.log(formData)
}
return (
<div>
<form onSubmit={handleSubmit}>
{/* form stuff */}
</form>
</div>
)
}
export default Edit
Basically, I'm taking the post object from my redux store and using those values to set my state in my component.基本上,我从我的 redux 商店中获取 object 帖子,并使用这些值在我的组件中设置我的 state。 This, of course, is loading before my api comes back with my post data so I get undefined.
当然,这是在我的 api 与我的帖子数据一起返回之前加载的,所以我没有定义。
I've tried setting state under我试过在下面设置 state
if (!post) { return <div>Loading...</div>}
but I get an infinite loop.但我得到一个无限循环。
I've even tried something like我什至尝试过类似的东西
useState({
title: post? post.attributes.title : '',
body: post? post.attributes.body : ''
}
But that's not working.但这行不通。
In other apps, I used a kind of container element for my form and passed the model as a prop, but I'm not sure if I need to do that or if there's a better way.在其他应用程序中,我为我的表单使用了一种容器元素,并将 model 作为道具传递,但我不确定是否需要这样做,或者是否有更好的方法。
If your initial value of post is null
then you need to guard your initial state data with optional Chaining
this as如果您的 post 初始值为
null
那么您需要使用optional Chaining
来保护您的初始 state 数据
const [formData, setFormData] = useState({
title: post?.attributes?.title || '',
body: post?.attributes?.body || ''
})
You are firing the API call when the component is mounted which will update the post state in the store.您在安装组件时触发 API 调用,这将更新商店中的 state 帖子。 What you need is another use Effect which will watch for the post and fires when it changes.
您需要的是另一种使用效果,它将监视帖子并在它更改时触发。
useEffect(() => {
if(post){
setFormData({
title: post?.attributes?.title || '',
body: post?.attributes?.body || ''
})
}
}, [post])
Add post as the dependency in the useEffect
.在
useEffect
中添加 post 作为依赖项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.