使用 hooks 时无法获取 props in react
It is not possible to get props in react when using hooks
我用函数替换了所有 类,并试图在另一个函数中获取状态。 this.props 没有 super(props) 是看不到的,否则获取它是行不通的。求助,先谢谢大家了!
// 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
广告代码截图
enter image description here
接收尝试代码截图
enter image description here
您不能像您的代码那样访问状态变量。 App.data
错了!
您应该使用 prop drilling 来传递要在子级中使用的父级数据。
const App = () => {
const [data, setData] = useState();
return (
<PostListItem data={data} />
);
}
const PostListItem = (props) => {
return (
<div>{props.data}</div>
)
}
我用函数替换了所有 类,并试图在另一个函数中获取状态。 this.props 没有 super(props) 是看不到的,否则获取它是行不通的。求助,先谢谢大家了!
// 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
广告代码截图 enter image description here
接收尝试代码截图 enter image description here
您不能像您的代码那样访问状态变量。 App.data
错了!
您应该使用 prop drilling 来传递要在子级中使用的父级数据。
const App = () => {
const [data, setData] = useState();
return (
<PostListItem data={data} />
);
}
const PostListItem = (props) => {
return (
<div>{props.data}</div>
)
}