2016-01-04 38 views
0

我試圖使用帶有一個ES6狀態作出反應成分,但是當我定義了一個構造函數,同時組件被渲染多次(從它的父構造函數只會被調用一次保持狀態的組件作出反應)。示例如下所示。我如何使用ES6

class SubComponent extends React.Component { 
    constructor(props) { 
    super(props); 
    console.log("Creating sub component"); 
    this.state = { count: props.count }; 
    } 

    render() { 
    console.log("Rendering sub component", this.state.count); 
    return (<div>count: {this.state.count}</div>); 
    } 
} 

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    console.log("Creating app"); 
    this.state = { count: 0 }; 
    this.tick = this.tick.bind(this); 
    setInterval(this.tick, 1000); 
    } 

    tick() { 
    this.setState({ count: this.state.count + 1 }); 
    } 

    render() { 
    console.log("Rendering app", this.state.count); 
    return (<SubComponent count={this.state.count} />); 
    } 
} 

這將不會更新渲染輸出(它總是會count: 0),但日誌將輸出:

Creating app 
Rendering app 0 
Creating sub component 
Rendering sub component 0 
Rendering app 1 
Rendering sub component 0 
Rendering app 2 
Rendering sub component 0 
Rendering app 3 
Rendering sub component 0 
... 

這裏有一個的jsfiddle:http://jsfiddle.net/jor0xu1a/1/

我知道的例子SubComponent不需要一個狀態,但我試圖儘可能簡單地顯示我的問題。

我錯過了什麼?

回答

2

我建議閱讀Props in getInitialState Is an Anti-Pattern

基本上,儘可能少的組件應該有狀態。正如其他答案已經說過,在你的情況下,你可以使用this.props.count來指代當前值。似乎沒有任何理由爲什麼SubComponent應該有自己的狀態。

但是,如果你真的想從它接收到的道具計算組件的狀態,這是你的責任,讓他們同步,與生命週期法componentWillReceiveProps

componentWillReceiveProps(nextProps) { 
    this.setState({count: nextProps.count}); 
} 
+0

,我會在這裏張貼了我的答案,如果我只看到你的帖子之前:)是啊,這是我相信的是,父母總是錯誤重新創建上重新渲染它的孩子。 'componentWillReceiveProps'解決了我的困境,謝謝你的幫助! –

3

在子是props不是狀態 - 將其更改爲this.props.count,這將工作

0

你子應該是:

class SubComponent extends React.Component { 
     constructor(props) { 
     super(props); 
     console.log("Creating sub component"); 
     } 

     render() { 
     return (<div>count: {this.props.count}</div>); 
     } 
    } 
0

我的壞,我想每當組件將被父重新渲染(用於ES5或getInitialState)調用構造函數(我認爲父母重新創建「其子女上渲染),但事實並非總是如此。我應該有它(url)念起來想這是一件我沒有ES6理解,在這裏創建一個問題之前,ES5(jsFiddle)試了一下。

是的,示例SubComponent應該使用this.props但我的用例在我的實際組件中有實際的有狀態功能。我創建了這個例子,因爲我認爲出於某種原因,使用ES6的結果並不是預期的結果(但它是)。

感謝您的反饋!