简体   繁体   English

如何使用 Redux 商店中的 useState 挂钩设置初始值?

[英]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.

相关问题 如何在笑话和酶中为 useState Hook 设置初始状态值? - How to set initial state value for useState Hook in jest and enzyme? 如何使用 useEffect 挂钩中设置的另一个 state 的值设置 useState 的初始值? - How to set the initial value of useState with the value of another state set in a useEffect hook? useState 初始值未设置 - useState initial value is not set 如何在 jest 和 enzyme 中为 useState Hook 设置初始 state? - How to set initial state for useState Hook in jest and enzyme? React-如何从Redux设置输入元素的初始值? - React - How to set initial value of input element from redux? 在执行 useState 之前设置 useState 钩子的初始值 - Setting the initial value of a useState hook before useState is executed 如何从 json 中分离键和值,并在反应中使用 useState 挂钩将其存储在数组中 - How to seperate keys and values from a json and store it in a array using useState hook in react 我想将从 firestore 中获取的数据设置为 useState 的初始值 - I want to set the fetched data from firestore as initial value of useState 如何根据 props 在 React 中设置初始 useState 值 - How to set initial useState value in React based on props 当一个初始状态用于通过 useState 钩子一次启动多个状态时,如何单独设置状态? - How to set states separately when an initial state is used to initiate several states at once with useState hook?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM