Home > OS >  It is not possible to get props in react when using hooks
It is not possible to get props in react when using hooks

Time:04-15

I replaced all classes with functions and am trying to get the state in another function. this.props does not see without super(props), and it does not work out to get it otherwise. I ask for help, thank you all very much in advance!

// Declaring the state via the useState hook;

    const App = () => {
        const [data, setData] = useState([
            {
                label: 'Учу React!',
                important: false,
                like: false,
                id: 1,
            },
    
            {
                label: 'Получается отлично ;)',
                important: false,
                like: false,
                id: 2,
            },
    
            {
                label: 'Не хочу останавливаться',
                important: false,
                like: false,
                id: 3,
            },
        ]);
    
        const [term, setTerm] = useState('');
        const [filter, setFilter] = useState('all');



// Attempt to get an array of data objects



    import React from 'react';
    import App from '../app/app';
    import { createContext } from 'react';
    import './post-list_item.css';
    
    const PostListItem = () => {
        console.log(App.data); // --> undefined

Screenshot of the ad code enter image description here

Screenshot of the code of the receiving attempt enter image description here

CodePudding user response:

You can't access state variable like your code. App.data is wrong!

You should use prop drilling to pass the parent data that you want to use in children.

const App = () => {
  const [data, setData] = useState();
  return (
    <PostListItem data={data} />
  );
}


const PostListItem = (props) => {
  return (
    <div>{props.data}</div>
  )
}
  • Related