简体   繁体   English

React-如何在render之外的函数中渲染组件以及如何在render之外执行相同的函数?

[英]React - How to render components inside a function outside of render plus execute same function outside of render?

I have a function outside of render. 我在render之外有一个功能。 That function returns (conditionally) a component, that function is beeing triggered not inside render, but inside componentWillReceiveProps (which was necessary due to other facts). 该函数返回(有条件地)一个组件,该函数不是在渲染内部而是在componentWillReceiveProps内部(由于其他事实而必需)触发的。 My problem is that the function does not end up returning the component and I dont know why. 我的问题是该函数最终不会返回该组件,我也不知道为什么。 When I call that function inside render, then of it works, but I cant do that as I must call it inside componentWillReceiveProps. 当我在render中调用该函数时,它可以工作,但是我不能做到这一点,因为必须在componentWillReceiveProps中调用它。 Any ideas? 有任何想法吗? Thanks!! 谢谢!!

class App extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.user != this.props.user) {
      this.getData(nextProps.user)
    }
  }

  getData() {
    if (...) {
      return <Child />
    }
  }

  render() {
    return (
      <div>{this.getData}</div>
    );
  }
}

const Child = () => {
  return <h1>Hello</h1>
}

Create a state called data in the constructor as follows: 在构造函数中创建一个名为data的状态,如下所示:

constructor(props){
    super(props);
    this.state={data:""};
}

Now, {this.getdata} inside render() with {this.state.data} 现在, {this.getdata}里面render(){this.state.data}

Also replace componentWillReceiveProps as follows: 还可以如下替换componentWillReceiveProps:

componentWillReceiveProps(nextProps) {
    if (nextProps.user != this.props.user) {
        var newdata = this.getData(nextProps.user)
        this.setState({data:newdata});
    }
}

You can only return JSX data in render and not in the other lifecycle function to render. 您只能在render中返回JSX数据,而不能在要渲染的其他生命周期函数中返回。 Also render method is pure so for the same input it returns the same output and hence react is able to rightly optimise on performance for the same by maintaining a virtual dom, so you would just write 而且render方法是纯净的,因此对于相同的输入,它返回相同的输出,因此react可以通过维护虚拟dom来正确地针对相同的性能进行优化,因此您只需编写

class App extends React.Component {
      getData() {
        if (...) {
            return <Child />
        }
      }
      render() {
          return (
              <div>
                {this.getData()}
              </div>
          )
      }
}

const Child = () => {
    return <h1>Hello</h1>
}

and it would have a the same effect, also if you further optimise by using React.PureComponent , so that render is called on when there is a prop change. 如果您使用React.PureComponent进一步优化,那么它也将具有相同的效果,以便在更改道具时调用render。 React.PureComponent implements shouldComponentUpdate with a shallow prop and state comparison. React.PureComponent通过浅层shouldComponentUpdate和状态比较实现了shouldComponentUpdate

class App extends React.PureComponent {
      componentWillReceiveProps(nextProps) {
         if (nextProps.user != this.props.user) {
         this.getData(nextProps.user)
         }
      }
      getData() {
        if (...) {
            return <Child />
        }
      }
      render() {
          return (
              <div>
                {this.getData()}
              </div>
          )
      }
}

However to do what you want, you would actually store the date in state of component and then render the data based on state in render method 但是,要执行您想要的操作,您实际上将日期存储在组件状态下,然后根据状态在render方法中渲染数据

class App extends React.Component {
      constructor(props) {
         super(props);
         this.state {
             data: this.getData(props)
         }
      }
      componentWillReceiveProps(nextProps) {
         if (nextProps.user != this.props.user) {
            this.getData(nextProps.user)
         }
      }
      getData(props) {
        if (...) {
            const newData;
            // update newData based on receivedProps here
            // store the data in state
            this.setState({data: newData});
        }
        return [];
      }
      render() {
          return (
              <div>
                {this.state.data.map((obj) => return <Child data={obj}/>)}
              </div>
          )
      }
}

Because you can't return children from other hooks than render you will need to keep them in a state: 因为除了render以外,您不能从其他挂钩中返回children ,所以您需要将它们保持在一个状态:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      someChildren: null
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.user != this.props.user) {
      this.setState({ someChildren: this.getData(nextProps.user) });
    }
  }
  getData() {
    if (...) {
      return <Child />;
    }
    return null
  }
  render() {
    return <div>{this.state.someChildren}</div>;
  }
}

When you component will receive new props, it will re-render automatically, doing like following you should have you component to re-render and being updated: 当您的组件将收到新的道具时,它将自动重新渲染,就像执行以下操作一样,使您的组件重新渲染并进行更新:

class App extends React.Component {
  getData: () => {
    if (...) {
      return <Child />
    }
    return null;
  };

  render() {
    return (
      <div>{this.getData()}</div>
    );
  }
}

componentWillReceiveProps is React lifecycle method which is invoked as soon as your React Component receive a prop by the parent. componentWillReceiveProps是React生命周期方法,一旦您的React Component收到父对象的支持,就会调用该方法。 Actions that could be performed in there are for example update the state what you are doing instead is calling a getDate method which is returning a React Component . 例如,可以在其中执行的操作将更新您正在做什么的状态,而不是调用getDate方法,该方法将返回React组件。

A possible implementation could be: 可能的实现方式可能是:

class App extends React.Component {

  getData() {
    const { user } = this.props;
    return user ? <Child /> : <div />
  }
  render() {
      return (
          <div>
            {this.getData()}
          </div>
      )
  }
}

const Child = () => {
  return <h1>Hello</h1>
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM