如何使用 React 钩子将道具同步到状态:setState() [英] How to sync props to state using React hooks : setState()

查看:82
本文介绍了如何使用 React 钩子将道具同步到状态:setState()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用组件接收的道具使用 React hook setState() 设置状态.我尝试使用以下代码:

import React,{useState, useEffect} from 'react';const Persons = (props) =>{//console.log(props.name);const [nameState , setNameState] = useState(props)console.log(nameState.name);console.log(props.name);返回 (<div><p>我的名字是{props.name},我的年龄是{props.age}</p><p>我的职业是{props.profession}</p>

)}导出默认人员;

问题是在加载组件时设置状态.但是当它收到新的 props 时,状态并没有得到更新.在这种情况下如何更新状态?提前致谢.

解决方案

useState hooks 函数参数仅使用一次,而不是每次道具更改时使用.您必须使用 useEffect 钩子来实现您将调用的 componentWillReceiveProps/getDerivedStateFromProps 功能

import React,{useState, useEffect} from 'react';const Persons = (props) =>{const [nameState , setNameState] = useState(props)useEffect(() => {设置名称状态(道具);}, [道具])返回 (<div><p>我的名字是{props.name},我的年龄是{props.age}</p><p>我的职业是{props.profession}</p>

)}导出默认人员;

I am trying to set the state using React hook setState() using the props the component receive. I've tried using the below code:

import React,{useState , useEffect} from 'react';

const Persons = (props) =>  {

    // console.log(props.name);

   const [nameState , setNameState] = useState(props)

   console.log(nameState.name);
   console.log(props.name);

   return (
            <div>
                <p>My name is {props.name} and my age is {props.age}</p>
                <p>My profession is {props.profession}</p>
            </div>
        )

}

export default Persons;

The issue is the state is being set upon component being loaded. But when it receive new props, the state is not getting updated. How to update the state in this case? Thanks in advance.

解决方案

useState hooks function argument is being used only once and not everytime the prop changes. You must make use of useEffect hooks to implement what you would call the componentWillReceiveProps/getDerivedStateFromProps functionality

import React,{useState , useEffect} from 'react';

const Persons = (props) =>  {
   const [nameState , setNameState] = useState(props)

   useEffect(() => {
       setNameState(props);
   }, [props])

   return (
            <div>
                <p>My name is {props.name} and my age is {props.age}</p>
                <p>My profession is {props.profession}</p>
            </div>
        )

}

export default Persons;

这篇关于如何使用 React 钩子将道具同步到状态:setState()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆