javascript How should I alternate componentWillMount()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52092341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I alternate componentWillMount()?
提问by Taichi
I'm using React.js, and as you know, componentWillMount() is going to be deprecated.
I wanna replace my componentWillMounts.
I'm using React.js, and as you know, componentWillMount() is going to be deprecated.
I wanna replace my componentWillMounts.
I'm going to move its logics into constructor. Is there any difference between executing some logic in componentWillMountand in constructor?
I'm going to move its logics into constructor. Is there any difference between executing some logic in componentWillMountand in constructor?
For example,
For example,
before
before
class Hello extends React.Component {
componentWillMount() {
doSomething();
}
render() {
return <div>{this.state.name} </div>
}
}
after
after
class Hello extends React.Component {
constructor(props) {
super(props);
doSomething();
}
render() {
return <div>{this.state.name} </div>
}
}
Also, when doSomething is setState, is there any difference setting state in constructor and in public prop?
Also, when doSomething is setState, is there any difference setting state in constructor and in public prop?
in constructor
in constructor
constructor(props) {
super(props);
this.state = { foo: 1 };
}
in public prop
in public prop
state = { foo: 1 };
回答by Bhojendra Rauniyar
constructoris not the right place for performing some actions. Because it will hold other operations until it's finished.
constructoris not the right place for performing some actions. Because it will hold other operations until it's finished.
componentDidMountis the right choice because it's an asynchronous function so that actions are run in the background and there'll be no hamper in the UI rendering.
componentDidMountis the right choice because it's an asynchronous function so that actions are run in the background and there'll be no hamper in the UI rendering.
Here's a listthat you can choose when to use between constructorand componentDidMount:
Here's a listthat you can choose when to use between constructorand componentDidMount:
constructor
constructor
Do:
Do:
- initialize state
- bind event handlers
- initialize state
- bind event handlers
If you don't initialize a state and you don't bind methods, you don't need to implement the constructor.
If you don't initialize a state and you don't bind methods, you don't need to implement the constructor.
Don't:
Don't:
Avoid introducing any side-effects or subscriptions. Do not set state by using setState() in the constructor.
Avoid introducing any side-effects or subscriptions. Do not set state by using setState() in the constructor.
componentDidMount
componentDidMount
Do:
Do:
- initialization that requires DOM nodes
- load data from a remote endpoint (where to instantiate the network request)
- set up any subscriptions (don't forget to unsubscribe in componentWillUnmount())
- initialization that requires DOM nodes
- load data from a remote endpoint (where to instantiate the network request)
- set up any subscriptions (don't forget to unsubscribe in componentWillUnmount())
You may also be interested to read the commentfrom the creator of react, Dan Abramov:
You may also be interested to read the commentfrom the creator of react, Dan Abramov:
I won't like to wait for the component to be mounted to dispatch an ajax call to fulfill the component data dependencies. I would like to do it as soon as possible, like in the constructor, not even in componentWillMount.
If it's an async request, it won't be fulfilled by the time the component mounts anyway, regardless of where you fire it. This is because JS is single threaded, and the network request can't "come back" and be handled while we are still rendering. So the difference between firing it earlier and later is often negligible.
You're right that it matters in some rare cases though and for those cases it might make sense to break the recommendation. But you should be extra cautious as state can update before mounting, and if your data depends on state, you might have to refetch in that case. In other words: when in doubt, do it in componentDidMount.
The specific recommendation to avoid side effects in the constructor and Will* lifecycles is related to the changes we are making to allow rendering to be asynchronous and interruptible (in part to support use cases like this better). We are still figuring out the exact semantics of how it should work, so at the moment our recommendations are more conservative. As we use async rendering more in production we will provide a more specific guidance as to where to fire the requests without sacrificing either efficiency or correctness. But for now providing a clear migration path to async rendering (and thus being more conservative in our recommendations) is more important.
I won't like to wait for the component to be mounted to dispatch an ajax call to fulfill the component data dependencies. I would like to do it as soon as possible, like in the constructor, not even in componentWillMount.
If it's an async request, it won't be fulfilled by the time the component mounts anyway, regardless of where you fire it. This is because JS is single threaded, and the network request can't "come back" and be handled while we are still rendering. So the difference between firing it earlier and later is often negligible.
You're right that it matters in some rare cases though and for those cases it might make sense to break the recommendation. But you should be extra cautious as state can update before mounting, and if your data depends on state, you might have to refetch in that case. In other words: when in doubt, do it in componentDidMount.
The specific recommendation to avoid side effects in the constructor and Will* lifecycles is related to the changes we are making to allow rendering to be asynchronous and interruptible (in part to support use cases like this better). We are still figuring out the exact semantics of how it should work, so at the moment our recommendations are more conservative. As we use async rendering more in production we will provide a more specific guidance as to where to fire the requests without sacrificing either efficiency or correctness. But for now providing a clear migration path to async rendering (and thus being more conservative in our recommendations) is more important.
For further interest, you may also visit this post.
For further interest, you may also visit this post.
回答by jordrake
setState in a constructor will perform unnecessary computation, you can either use the state property as you suggest or this.state = { ... }in your constructor if you need to perform more computation or access props.
setState in a constructor will perform unnecessary computation, you can either use the state property as you suggest or this.state = { ... }in your constructor if you need to perform more computation or access props.
The React documentationrecommends you use constructor (or a class property) over componentWillMount for initialising state. For side-effects (e.g. http request) that could update state you should consider componentDidMount or componentDidUpdate. With asynchronous state updates, you should always make sure that your component handles the state without that data.
The React documentationrecommends you use constructor (or a class property) over componentWillMount for initialising state. For side-effects (e.g. http request) that could update state you should consider componentDidMount or componentDidUpdate. With asynchronous state updates, you should always make sure that your component handles the state without that data.
回答by Priyanka Gupta
getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing. So If you want to perform some action just once, on before mount of component, then getDerivedStateFromProps is not appropriate option.
getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing. So If you want to perform some action just once, on before mount of component, then getDerivedStateFromProps is not appropriate option.
Use componentDidMount method. Have more details in https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html
Use componentDidMount method. Have more details in https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html
回答by Kary
Use getDerivedStateFromProps()it's next method called after constructor.
Use getDerivedStateFromProps()it's next method called after constructor.
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

