2016-12-26 61 views
0

我使用ReactDOM.render來渲染一個元素,但它完全覆蓋了它內部的現有節點。我不想綁定任何類似redux的狀態功能,我只想渲染一個字符串並追加到一個元素。這可能嗎?附加React組件沒有ANY REDX?

我懷疑人們會告訴我只是使用狀態和什麼不是,但我想我的後續問題是,我有一個元素,將有數百/數千的圖像,它會重新呈現每次使用React?操縱數千個物體的狀態會變慢嗎?

+0

如果有數千張圖片在部分我想你應該做一個子組件來實現該功能 – Chathuranga94

+0

@ Chathuranga94莫非你點我會教一些材料我如何有效地做到這一點? – user3730954

回答

0

正在考慮上市的產品的例子:

https://jsfiddle.net/pf7z8z4m/12/

class Product extends React.Component{ 

    shouldComponentUpdate(nextProps, nextState) { 
    return (this.props.product !== nextProps.product) 
    } 

    render(){ 
    console.log('rendering product '+this.props.product.name) 
    return (<li> 
     <h4>{this.props.product.name}</h4> 
     <img src={this.props.product.img} alt={this.props.product.name}/> 
     </li>) 
    } 
} 

class ProductList extends React.Component{ 
    render(){ 
    const items = this.props.products.map((product)=> 
      <ul key={product.id}> 
     <Product product={product}/> 
     </ul>) 
    return (<ul>{items}</ul>) 
    } 

} 

class App extends React.Component{ 
    constructor(props){ 
    super(props) 
    this.state = {products:[]} 

    //following is just a simple simulation of products being added to the list through time 
    setTimeout(
     ()=>{this.setState({products:[...this.state.products, 
     {id:1,name:'Product A', img:'productA.png'}]})}, 
     1000 
     ) 
    setTimeout(
     ()=>{this.setState({products:[...this.state.products, 
     {id:2,name:'Product B', img:'productB.png'}]})}, 
     3000 
     ) 
    setTimeout(
     ()=>{this.setState({products:[...this.state.products, 
     {id:3,name:'Product C', img:'productC.png'}]})}, 
     5000 
     ) 
    } 

    render(){ 
    return (<ProductList products={this.state.products}/>) 
    } 
} 

React.render(<App/>,document.getElementById('root')) 

中的新元素(產品)正在定期添加到列表中,但不會導致對其他部分重新渲染。

Product上的方法shouldComponentUpdate正在控制該方法。另一種選擇是擴展React.PureComponent。

看看這個文檔:

https://facebook.github.io/react/docs/optimizing-performance.html