React+ 将整个状态对象发送到另一个组件

React+ sending entire state object to another component

很简单但很困惑,

我有一个父组件,状态为 这是我的

this.state = { 待办事项名称:“”, 待办事项列表:[], "isAvail":是的, "IsArchive":假 };

在我的父组件中调用子组件

<ChildComponent data= {this.state} />

但在渲染器中的 childCompoenent 中,我尝试调用 like

const isAvail = this.props.data.isAvail;
const isArchieve = this.props.data.isArchieve;

如果我这样调用 {isAvail} 并且在内部重新运行,我没有得到并且收到错误

对象作为 React 子项无效(找到:具有键 {todoName、todoList、isAvail、IsArchive} 的对象)。如果您打算呈现子项集合,请改用数组。

但不知何故我需要得到完整的对象..这怎么可能

你可以这样称呼

render() {
  const {isAvail, isArchieve} = this.props.data;
  return(<div><p>{isAvail}</p></div>);
}
class Parent extends React.Component{
  constructor(props){
    super(props)
    this.state= {
      todoName: "passed from parent", todoList: [], "isAvail":true, "IsArchive":false
     }
  }
  render(){
    return <Child data={this.state}/>
 }
}

const Child = (props) => <div>{props.data.todoName}{console.log(props)}</div>

Live Demo

你知道 ContextAPI 并且你想在不使用 props drilling 的情况下发送数据,请使用 ContextAPI。在某些情况下,我们也可以在使用上下文 API.

时将状态值用于子组件

在你的父组件中创建上下文

const ParentState = React.createContext()

 render() {
   <ParentState.Provider value={{ data: this.state }}>
            <Childcomponent/>
   </ParentState.Provider>
}

在子组件中导入Context并使用

 render() {
   return(
      <ParentState.Consumer>
          {
             parentState => (<div><p>{parentState.data.isAvail}</p></div>)
          }
      </ParentState.Consumer>
   )
}