注意:本篇文章是根據(jù)上一篇文章進行修改的,如果需要源碼,請去上一篇文章中進行復(fù)制! 源碼-傳送門
cnpm i -D react-redux
1.引入react-redux (src/index.js)
import {Provider} from 'react-redux'
2.使用Provider (src/index.js)
//store參數(shù)是必須參數(shù)
render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById("root")
);
這樣引用之后在App下所有組件中都可以獲取到store中的內(nèi)容
3.使用store的內(nèi)容 (src/components/CartList/index.js)
import {connect} from 'react-redux'
4.修改導(dǎo)出方式src/components/CartList/index.js
export default connect()(CartList);
此時如果在render函數(shù)中輸出this.props結(jié)果應(yīng)該為dispatch的一個函數(shù)
5.繼續(xù)修改導(dǎo)出方式src/components/CartList/index.js
const mapStateToProps=(state)=>{
return{
cartList:state.Cart
}
}
export default connect(mapStateToProps)(CartList);
參數(shù)mapStateToProps為當(dāng)前的this.props添加屬性
mapStateToProps的參數(shù)state就是在src/index.js傳入的store的值
6.繼續(xù)修改導(dǎo)出方式src/components/CartList/index.js
import {increment,decrement} from '../../actions/cart'
export default connect(mapStateToProps,{decrement,increment})(CartList);
connect第二個參數(shù),在props中添加待執(zhí)行函數(shù)
7.修改遍歷時的render
class CartList extends Component {
render() {
return (
<table>
<thead>
<tr>
<th>編號</th>
<th>商品名稱</th>
<th>價格</th>
<th>數(shù)量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{/*遍歷當(dāng)前組件的數(shù)據(jù)*/}
{
this.props.cartList.map(item=>{
return(
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.title}</td>
<td>{item.price}</td>
map<td>
{/*dispatch是自動生成,用來調(diào)用函數(shù)的 如果需要修改狀態(tài)值,就必須使用dispatch來調(diào)用*/}
<button onClick={()=>{
this.props.decrement(item.id)
}}>-</button>
<span>{item.amount}</span>
<button onClick={()=>{
this.props.increment(item.id)
}}>+</button>
</td>
<td></td>
</tr>
)
})
}
</tbody>
</table>
);
}
}