2016-12-02 52 views
1

我有父項組件中的項目列表,並且在其中添加了新項目和更新項目。子組件將接收道具中的物品並進行渲染。父組件正在更新其數組時,父組件未更新

當父狀態得到更新時,子組件未更新其值。 我是否需要更新「componentWillReceiveProps」中子組件狀態的狀態?什麼是正確的做法。

Code Example 
// parent component 
import React, { Component } from "react"; 
import TestList from '../controls/testlistview' 

export default class TestView extends Component { 
    constructor(props) { 
     super(); 
     this.state = { 
      items: [] 
     }; 
    } 

    render() { 
     return (<div> 
      <button onClick={this.addItem.bind(this)}> Add item</button> 
      <button onClick={this.changeFirstItemText.bind(this)}> Change item</button> 
      <TestList items={this.state.items} index={index}/> 
     </div>); 
    } 

    addItem() { 
     var items = this.state.items.map(s=> s); 

     items.push('new one'); 
     this.setState({ 
      items: items 
     }); 
    } 



    changeFirstItemText() { 
     var items = this.state.items.map(s=> s); 
     items[0] = "changed text"; 
     this.setState({ 
      items: items 
     }); 
    } 
} 



//Child component 
import React, { Component } from "react"; 

export default class TestList extends Component { 
    constructor(props) { 
     super(); 
     debugger; 
     this.state = { 
      rootNodes: props.items 
     }; 
    } 

    componentWillReceiveProps(nextProps){ 
     debugger; 
    } 

    render() { 
     var items = this.state.rootNodes.map((s) => { 
      return <div>{s}</div>; 
     }); 
     return <div>{items}</div>; 
    } 
} 
+0

爲什麼你的孩子有自己的國家呢? – azium

回答

1

而不是

render() { 
     var items = this.state.rootNodes.map((s) => { 
      return <div>{s}</div>; 
     }); 
     return <div>{items}</div>; 
    } 

您獲得的道具物品

render() { 
     var items = this.props.items.map((s) => { 
      return <div>{s}</div>; 
     }); 
     return <div>{items}</div>; 
    } 

您不必再指定道具TestList狀態,否則,你將需要做的setState( )從TestList中再次觸發渲染。 (這是不是necesary步驟)

http://codepen.io/kossel/pen/ObQLoR

0

在你不應該指定道具到組件的狀態TestList類 - 這是一個正確的方式來引起陣營的重大問題,並且是您事業問題在這裏。看到my answer here爲什麼這是一個壞主意。

如果您將您的TestItem更改爲以下,那麼它應該工作正常。

export default class TestList extends Component { 
    constructor(props) { 
     super(); 
     debugger; 
    } 

    componentWillReceiveProps(nextProps){ 
     debugger; 
    } 

    render() { 
     var items = this.props.items.map((s) => { 
      return <div>{s}</div>; 
     }); 
     return <div>{items}</div>; 
    } 
} 
0

原因是您正在通過子組件的狀態創建ui元素。 有解決這個問題的方法有兩種:UI元素直接從道具價值
1.更新的componentWillReceiveProps(狀態值)funtion這樣

componentWillReceiveProps(newProps){ 
     this.setState({ 
      rootNodes: newProps.items 
     }); 
} 

2.創建像這個 -

render() { 
    var uiItems = this.props.items.map((item) => { 
     return <div>{item}</div>; 
    }); 
    return (<div>{uiItems}</div>); 
} 
+0

謝謝。我需要操作道具和創建狀態項目,所以第一個選項可行,但我的問題是,這是否是正確的方法呢? –

+0

這兩種方式都是正確的,當你想存儲組件的一些信息時使用狀態變量,在這種情況下,你正在創建固定的UI元素,所以更好的方式將是第二個,讓我們說你正在創建一些文本字段或任何其他用戶可以改變的用戶界面,那麼第一選項在這種情況下會更好。 –

+0

在我真正的應用它不只是固定的用戶界面多數民衆贊成爲什麼使用狀態。感謝你的回答。 –