简体   繁体   中英

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

I'm getting some data from a third-party API. I must do some operations in one of the values we receive (price). The modifications are being done successfully at the Action creator and stored in a new array called price, and being passed as props.

The individual Product component is being rendered after using the map method on the array of products.

My question is, how do I pass the new array (modified price) down to this Product component (and apply it for the correct product).

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

    </View>
 )
};

As the new price is being added as 'price' prop. I naturally tried <Product price={props.price} key={product.index} {...product} /> which ends up displaying the entire array of prices on each product.

I also tried converting this array into an array of objects, and spreading it <Product key={product.index} {...product} {...props.price}/> but this doesn't seem to work either.

What would be your best approach to this type of situation?

I would do this logic in a selector and use reselect to memoize it: https://github.com/reactjs/reselect .

If you aren't already using selectors that is a pretty well acknowledged best practice for handling derived data: https://gist.github.com/abhiaiyer91/aaf6e325cf7fc5fd5ebc70192a1fa170

If productList and priceList arrays have the same length you can use index to get matching price from priceList array for current product and pass it as 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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