简体   繁体   English

无法访问 state 中的 React 道具

[英]Cannot access React props in state

I'm passing some data from parent to children like the following我正在将一些数据从父母传递给孩子,如下所示

<Children title={title}/>

Inside the children I have a state like this:在孩子们里面我有一个像这样的 state:

const [state,setState] = useState(title ? title : '')

Problem is, when accessing the title directly like this {title} it's working, accessing state on the other hand does not work.问题是,当像{title}那样直接访问标题时,它正在工作,另一方面,访问state不起作用。 Should I useEffect for this to get data from parent when the state is loaded?加载useEffect时,我应该为此使用 Effect 从父级获取数据吗?

Access the props in the children component like this -像这样访问子组件中的props -

function childComponent(props) {
  //props.title -- access it in your component.
}

But what you're trying in your code is not recommended, you can't mutate the state of props.但是不推荐您在代码中尝试的内容,您不能改变道具的 state 。 Read React docs阅读 React 文档

You need to use useEffect hook here.你需要在这里使用useEffect钩子。 because useState is basically used to initialize the value and not to update.因为useState基本上是用来初始化值而不是更新。

useEffect(() => {
   setState(title);
}, [title]);

Because the problem with your approach is that when you do -因为您的方法的问题在于,当您这样做时-

const [state,setState] = useState(title ? title : '')

This will set your state variable to '' (empty string) because on the initial render of your child component there is no guarantee that you are going to get the value of title .这会将您的state变量设置为'' (空字符串),因为在您的子组件的初始渲染中,无法保证您将获得title的值。 And when you get the value of title in your props.当你在你的道具中获得title的价值时。 useState will not detect it. useState不会检测到它。
So therefore to detect a change in your props and to setState based on updated props its recommended to use useEffect .因此,为了检测道具的变化并根据更新的道具设置状态,建议使用useEffect

This is the correct implementation of this;这是正确的实现;

<ClassA title = "class a"/>



function ClassA(props){
// access the title by calling props.title
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM