美文网首页
react中通过props给子组件传值,为什么当父组件setSt

react中通过props给子组件传值,为什么当父组件setSt

作者: pomelo_西 | 来源:发表于2019-02-28 17:19 被阅读0次

    父组件代码

    class AssetDetail extends React.Component {
      state={
        asset: {}
      }
      render() {
        return (
          <AssetMarket asset={{...asset}} />
        )
      }
    }
    

    当父组件setState变化asset值,就会重新渲染
    子组件使用asset里的属性做渲染,直接使用this.props.asset.属性名可以实时刷新

    class AssetMarket extends Component {
      render() {
        <div className='stratified'>
          {
             this.props.asset.stratified.buy.map((item, index) =>
               <Row key={index} className='stratified-item'>
                 <Col span={10} className='item-price text-right is-green'>{item.price}</Col>
                 <Col span={8} title={item.number} style={{overflow: 'hidden', textOverflow: 'ellipsis'}} className='item-number text-center'>
                   {item.number % 1000000 === 0 ? parseFloat(item.number / 1000000) : parseFloat(item.number / 1000000).toFixed(3)}
                  </Col>
                 </Row>
             )
           }
         </div>
      }
    }
    

    这里因为子组件是拿asset里的某个属性做渲染,所以父组件里直接使用

    <AssetMarket asset={asset} />
    

    这样只是里面的某个属性的值发生了变化,没有觉得asset发生变化,所以子组件不能重新渲染

    所以使用

    <AssetMarket asset={{...asset}} />
    

    重新new 一个asset对象

    第二种解决方案,将需要实时刷新的值直接传给子组件

    <AssetMarket stratifiedBuy={asset.stratified.buy} stratifiedSell={asset.stratified.sell}/>
    

    子组件

    this.props.stratifiedBuy
    

    也可以实现实时刷新

    相关文章

      网友评论

          本文标题:react中通过props给子组件传值,为什么当父组件setSt

          本文链接:https://www.haomeiwen.com/subject/rjiseqtx.html