简体   繁体   中英

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:

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. Should I useEffect for this to get data from parent when the state is loaded?

Access the props in the children component like this -

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. Read React docs

You need to use useEffect hook here. because useState is basically used to initialize the value and not to update.

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 . And when you get the value of title in your props. useState will not detect it.
So therefore to detect a change in your props and to setState based on updated props its recommended to use useEffect .

This is the correct implementation of this;

<ClassA title = "class a"/>



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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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