简体   繁体   English

如何通过在无状态组件中的开关内调用函数来更新父状态?

[英]How can I update the parent state by calling a function within a switch in my stateless component ?

My goal is to update the state of my parent component with only a portion of data from the initial Json 我的目标是仅使用初始Json中的一部分数据来更新父组件的状态

So basically if for example the case text get triggered: 所以基本上,例如,如果触发案例text

1- I return the desired text and render it in my component (I succeeded in doing that) 1-我返回所需的text并将其呈现在我的组件中(我成功完成了此操作)

2- I also want to take this specific data and store it in the parent state 2-我也想获取此特定数据并将其存储在父状态中

3- I will later use this data to create a form 3-我稍后将使用这些数据来创建表格

I tried many things, I finally managed to update the state of the parent by passing down a function to the stateless function MyFunction , but I keep getting a warning because the setState is being called inside the render method of the parent Component 我尝试了很多事情,最终通过将函数传递给无状态函数MyFunction来设法更新了父级的状态,但是由于收到setStateparent Componentrender方法中被调用的消息,所以我不断收到警告。

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Warning: Cannot update during an existing state transition (such as within渲染or another component's constructor). Warning: Cannot update during an existing state transition (such as within or another component's constructor).

const MyFunction = props => {

   switch (props.type) {
       case 'image':
         return  props.json.data[props.key]
         break
       case 'text':
         props.changeParent(props.json.data[props.key])
         return props.json.data[props.key]
         break
       default:
         return "Empty text"
         break
  }
}

class UserComponent extends Component {
 constructor(props){
  super(props)
    this.state = {
     active: false
    }
 }

render(){
  return(
    <div>
      { MyFunction({ type: 'text', key: 'first_name', ...this.props }) }
      <img src={ MyFunction({ type: 'image', key: 'avatar', ...this.props }) } />
    </div>
   )
 }
}

// Parent Component
class App extends Component {
 constructor(props){
  super(props)
  this.state = {
    json:[],
    newJson: []
  }
}

// Fetching data from an api
componentDidMount(){
fetch("https://reqres.in/api/users/2")
   .then(response => response.json())
   .then(json => {
      this.setState({json: json })
 })
}

// Update the parent Json using the data sent from the 2nd child
changeParent(jsonToUpdate){
  this.setState({
    newJson :
       jsonToUpdate
    })
 }

render() {
  return (
    <div>
      <UserComponent {...this.state} changeParent={(jsonToUpdate) => this.changeParent(jsonToUpdate)}/>
    </div>
  );
 }
}

export default App;

Just use componentDidMount lifecycle method and maintain a state for the data returned by myFunction to avoid that warning like this 只需使用componentDidMount生命周期方法并维护myFunction返回的数据的状态即可避免出现此类警告

class UserComponent extends Component {
 constructor(props){
  super(props)
    this.state = {
     active: false,
     // this state stores the data returned by function
     myFunctionReturnData: ""
    }
 }

componentDidMount(){
  let myFunctionReturnData = MyFunction({ type: 'text', key: 'first_name', ...this.props });
  // Call the function and set the state by returned value
  this.setState({ myFunctionReturnData })
}
render(){
  return(
    <div>
      // Will render returned value when state will be set
      { this.state.myFunctionReturnData }
      <img src={ MyFunction({ type: 'image', key: 'avatar', ...this.props }) } />
    </div>
   )
 }
}

Update:: 更新::

If you are calling MyFunction multiple times then you should avoid calling changeParent inside MyFunction because you are calling MyFunction inside render and calling changeParent inside render will put this in loop because you are updating parent state in changeParent function. 如果您多次调用MyFunction ,则应避免在MyFunction内部调用changeParent ,因为您在render内部调用MyFunction在render内部调用changeParent会将其置于循环中,因为您正在changeParent函数中更新父状态。 A better solution i can think of according to given code is this 我可以根据给定的代码想到一个更好的解决方案是

const MyFunction = props => {

   switch (props.type) {
       case 'image':
         return  props.json.data[props.key]
         break
       case 'text':
         // Remove changeParent from here
         return props.json.data[props.key]
         break
       default:
         return "Empty text"
         break
  }
}

And in componentDidMount use MyFunction to call the changeParent like 在componentDidMount中使用MyFunction调用changeParent

componentDidMount(){
  let myFunctionReturnData = MyFunction({ type: 'text', key: 'first_name', ...this.props });
  // Call the parent function
  this.props.changeParent(myFunctionReturnData)
}

You do not need to maintain any state now. 您现在不需要维护任何状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从子组件更新我的父 state? - How can I update my parent state from child component? 使用无状态函数定义组件时如何初始化状态 - How can I Initialize the state when using a stateless function to define my component 如何通过在父组件中调用函数来更改子组件内的状态? - How do I change state within a child component by calling function in its parent? 如何在条件中另一个组件下方的无状态组件上呈现函数? - How can I render a function on a stateless component just below another component within a conditional? 如何在 React 中从父 class 更新我的子组件 state? - How can I update my child component state from the parent class in React? 如何将具有切换 function 的 state 组件转换为 reactjs 中的无状态组件? - How can I convert a state component that has a toggle function to a stateless one in reactjs? 从无状态子组件更改我的父组件的状态 - Changing the state of my parent component from a stateless child component React - 如何使用子组件设置我的父 state,使用 function 结构(不是类) - React - How can I set my parent state using child component, using function structures (not classes) 反应无状态子组件不会在父组件的状态更改时更新 - react stateless child components do not update on state change in parent component Redux状态更新不会传递到组件的无状态函数中的方法 - Redux state updates don't pass through to a method within my component's stateless function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM