繁体   English   中英

将多个数组传递到同一组件的React / Redux最佳实践

[英]React/Redux Best practices on passing multiple arrays to same component

我从第三方API获取一些数据。 我必须对我们收到的值之一(价格)进行一些操作。 修改已在Action创建者处成功完成,并存储在名为price的新数组中,并作为道具传递。

在产品数组上使用map方法后,将渲染单个Product组件。

我的问题是,如何将新数组(修改后的价格)传递给该产品组件(并将其应用于正确的产品)。

const CoinList = (props) => {
 return(
    <View>
            {
                props.productList.map(product => {
                    return <Product key={product.id} {...product}/>
                })
            }

    </View>
 )
};

随着新价格被添加为“价格”道具。 我自然尝试了<Product price={props.price} key={product.index} {...product} /> ,最终显示了每个产品的全部价格。

我还尝试将该数组转换为对象数组,然后将其传播<Product key={product.index} {...product} {...props.price}/>但这似乎也不起作用。

对于这种情况,您最好的方法是什么?

我将在选择器中执行此逻辑,然后使用reselect对其进行记忆: https : //github.com/reactjs/reselect

如果您尚未使用选择器,那是公认的处理派生数据的最佳做法: https : //gist.github.com/abhiaiyer91/aaf6e325cf7fc5fd5ebc70192a1fa170

如果productList和priceList数组的长度相同,则可以使用index从priceList数组中获取当前产品的匹配价格,并将其作为prop传递。

 class Product extends React.Component { render() { let {id, name, price} = this.props; return <div className="Product">{name} | {price} $</div> } } const CoinList = (props) => { return <div>{props.productList.map((product, i) => { return <Product price={props.priceList[i]} key={product.id} {...product}/>}) }</div> }; const products = [{id: 1, name: 'A'}, {id: 2, name: 'B'}] const prices = [100, 200] ReactDOM.render( <CoinList productList={products} priceList={prices} />, document.getElementById('app') ) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM