注意:本篇文章是根据上一篇文章进行修改的,如果需要源码,请去上一篇文章中进行复制! 源码-传送门
cnpm i -D react-redux
1.引入react-redux
(src/index.js
)
import {Provider} from 'react-redux'
2.使用Provider
(src/index.js
)
//store参数是必须参数
render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById("root")
);
这样引用之后在App下所有组件中都可以获取到store
中的内容
3.使用store
的内容 (src/components/CartList/index.js
)
import {connect} from 'react-redux'
4.修改导出方式src/components/CartList/index.js
export default connect()(CartList);
此时如果在render
函数中输出this.props
结果应该为dispatch
的一个函数
5.继续修改导出方式src/components/CartList/index.js
const mapStateToProps=(state)=>{
return{
cartList:state.Cart
}
}
export default connect(mapStateToProps)(CartList);
参数mapStateToProps
为当前的this.props
添加属性
mapStateToProps
的参数state
就是在src/index.js
传入的store
的值
6.继续修改导出方式src/components/CartList/index.js
import {increment,decrement} from '../../actions/cart'
export default connect(mapStateToProps,{decrement,increment})(CartList);
connect
第二个参数,在props
中添加待执行函数
7.修改遍历时的render
class CartList extends Component {
render() {
return (
<table>
<thead>
<tr>
<th>编号</th>
<th>商品名称</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{/*遍历当前组件的数据*/}
{
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是自动生成,用来调用函数的 如果需要修改状态值,就必须使用dispatch来调用*/}
<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>
);
}
}
网友评论