[英]How to properly pass an array from a parent React class component state to a child component written with hooks?
I'm trying to learn how to use react hooks properly.我正在尝试学习如何正确使用 React 钩子。 I have a parent component written with class and I'm trying to capture an array (rooms) in my new child component that is using hooks.我有一个用 class 编写的父组件,我试图在使用钩子的新子组件中捕获一个数组(房间)。 Here is a simplified version of the code:这是代码的简化版本:
Parent component父组件
export default class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
rooms: []
};
}
componentDidMount() {
RoomService.getAllRooms()
.then((res) => {
if (res.status === 200) {
var roomsArray = [...res.data];
this.setState({ rooms : roomsArray });
}
})
.catch((err) => console.log(err))
}
render() {
return (
<div>
<ChildComponent {...this.state.rooms}/>
</div>
);
} }
An this is my child component这是我的子组件
function ChildComponent (props) {
const [rooms, setRooms] = useState(props);
useEffect(() => {
console.log('props received ' + JSON.stringify({rooms}));
},[props]);
...
If I log my state inside the parent component I see the content of my array.如果我在父组件中记录我的状态,我会看到我的数组的内容。 But my child component is always displaying an array with no content.但是我的子组件总是显示一个没有内容的数组。
props received {"rooms":{}}
What am I doing wrong that I can't retrieve the content of my array inside the child component?我做错了什么,无法在子组件中检索数组的内容?
You should pass props by providing the prop name in parent component:您应该通过在父组件中提供道具名称来传递道具:
<ChildComponent rooms={this.state.rooms}/>
and in ChildComponent
:在ChildComponent
:
function ChildComponent ({rooms}) {
const [rooms, setRooms] = useState(rooms);
useEffect(() => {
console.log('props received ' + JSON.stringify(rooms));
},[rooms]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.