javascript 在 React.js 中拥有像 componentWillMount 这样的函数的目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30042978/
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
What is the purpose of having functions like componentWillMount in React.js?
提问by Adi Sivasankaran
I have been writing components in React.js recently. I have never had to use methods like componentWillMount
and componentDidMount
.
我最近一直在用 React.js 编写组件。我从来没有使用过像componentWillMount
和这样的方法componentDidMount
。
render
is indispensable. getInitialState
and other helper methods I wrote also come in handy. But not the two aforementioned lifecycle methods.
render
是必不可少的。 getInitialState
和我写的其他辅助方法也派上用场。但不是上述两种生命周期方法。
My current guess is that they are used for debugging? I can console.log out inside them:
我目前的猜测是它们用于调试?我可以在它们里面 console.log out:
componentWillMount: function() {
console.log('component currently mounting');
},
componentDidMount: function() {
console.log('component has mounted');
}
Are there any other uses?
还有其他用途吗?
回答by Cymen
componentDidMount
is useful if you want to use some non-React JavaScript plugins. For example, there is a lack of a good date picker in React. Pickadayis beautiful and it just plain works out of the box. So my DateRangeInput component is now using Pickaday for the start and end date input and I hooked it up like so:
componentDidMount
如果你想使用一些非 React JavaScript 插件,这很有用。例如,React 中缺少一个好的日期选择器。Pickaday很漂亮,而且开箱即用。所以我的 DateRangeInput 组件现在使用 Pickaday 作为开始和结束日期输入,我像这样连接它:
componentDidMount: function() {
new Pikaday({
field: React.findDOMNode(this.refs.start),
format: 'MM/DD/YYYY',
onSelect: this.onChangeStart
});
new Pikaday({
field: React.findDOMNode(this.refs.end),
format: 'MM/DD/YYYY',
onSelect: this.onChangeEnd
});
},
The DOM needs to be rendered for Pikaday to hook up to it and the componentDidMount
hook lets you hook into that exact event.
需要为 Pikaday 呈现 DOM 以连接到它,并且该componentDidMount
挂钩可让您连接到该确切事件。
componentWillMount
is useful when you want to do something programatically right before the component mounts. An example in one codebase I'm working on is a mixin that has a bunch of code that would otherwise be duplicated in a number of different menu components. componentWillMount
is used to set the state of one specific shared attribute. Another way componentWillMount
could be used is to set a behaviour of the component branching by prop(s):
componentWillMount
当您想在组件安装之前以编程方式执行某些操作时非常有用。我正在处理的一个代码库中的一个例子是一个 mixin,它有一堆代码,否则这些代码会在许多不同的菜单组件中重复。componentWillMount
用于设置一个特定共享属性的状态。componentWillMount
可以使用的另一种方法是通过 prop(s) 设置组件分支的行为:
componentWillMount() {
let mode;
if (this.props.age > 70) {
mode = 'old';
} else if (this.props.age < 18) {
mode = 'young';
} else {
mode = 'middle';
}
this.setState({ mode });
}
回答by Jon
componentDidMount
only runs once and on the client side. This is important, especially if you're writing an isomorphic app (runs on both the client and server). You can use componentDidMount to perform tasks require you to have access to window or the DOM.
componentDidMount
只在客户端运行一次。这很重要,特别是如果您正在编写同构应用程序(在客户端和服务器上运行)。您可以使用 componentDidMount 来执行需要访问窗口或 DOM 的任务。
From Facebook's React Page
来自 Facebook 的 React 页面
If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.
componentWillMount
has fewer use cases (I don't really use it), but it differs in that it runs both on the client and server side. You probably don't want to put event listeners or DOM manipulations here, since it will try to run on the server for no reason.
componentWillMount
用例较少(我并不真正使用它),但它的不同之处在于它同时在客户端和服务器端运行。您可能不想在此处放置事件侦听器或 DOM 操作,因为它会无缘无故地尝试在服务器上运行。
回答by dpwrussell
This is an example of an isomorphic web application that makes use of componentWillMount
: https://github.com/coodoo/react-redux-isomorphic-example
这是一个使用同构 Web 应用程序的示例componentWillMount
:https: //github.com/coodoo/react-redux-isomorphic-example
However, I'm 99% certain that it runs the code inside componentWillMount
for no reason on the server side (I think using componentDidMount
to ensure it was only run client side would have made more sense) as the code which ensures that fetch promises are fulfilled before rendering the page is in server.js not inside the individual components.
但是,我 99% 肯定它componentWillMount
在服务器端无缘无故地运行内部代码(我认为使用componentDidMount
确保它只在客户端运行会更有意义),因为确保获取承诺之前得到履行的代码呈现页面是在 server.js 中而不是在单个组件中。
There is discussion on per-component async fetching here: https://github.com/facebook/react/issues/1739As far as I can tell, there is not a good use case for componentWillMount
as far as isomorphism is concerned at least.
这里有关于每个组件异步获取的讨论:https: //github.com/facebook/react/issues/1739据我所知,componentWillMount
至少就同构而言,没有一个好的用例。
回答by Shubham Séthi
In my project which is a dashboarding tool, I have used componentDidMount().
在我的仪表板工具项目中,我使用了 componentDidMount()。
On home page previously saved dashboards appear on the sidebar. I make an ajax call within componentDidMount() of component rendering Homepage, so as to fetch list of dashboards asynchronously after the page has been rendered.
在主页上以前保存的仪表板出现在侧栏上。我在组件渲染主页的 componentDidMount() 中进行了 ajax 调用,以便在页面渲染后异步获取仪表板列表。
回答by Wayne Chiu
Why React Life Cycle Methods?
为什么要响应生命周期方法?
Intend to use third-party (Ex D3.js) library with React Component
打算在 React 组件中使用第三方(Ex D3.js)库
class Example extends React.component{
constructor(){
// init state
// will be called only once
}
componentWillMount(){
// will be called only once
// will not be triggered when re-rendering
// usually will fetch data that is needed in order
// to render properly from other API
}
shouldComponentUpdate(){
return false
// will not re-render itself after componentDidMount(){}
}
render(){
return (
<div id="chart"></div>
)
}
componentDidMount(){
d3.select(".chart")
.selectAll("p")
// d3.js ........
// d3.js ........
// Usually, this will trigger React to re-render itself,
// but this time will not because we have set
// shouldComponentUpdate to false
}
}
Why React wants to do this?
为什么 React 想要这样做?
Since rendering DOM is an expensive operation, React uses the layer of virtual DOM to update only DOM / DOMs that is/are different from previous state.
由于渲染 DOM 是一项昂贵的操作,因此 React 使用虚拟 DOM 层仅更新与之前状态不同的 DOM / DOM。