美文网首页
20.react-redux

20.react-redux

作者: __疯子__ | 来源:发表于2020-06-01 09:57 被阅读0次

注意:本篇文章是根据上一篇文章进行修改的,如果需要源码,请去上一篇文章中进行复制! 源码-传送门

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>
        );
    }
}

相关文章

  • 20.react-redux

    注意:本篇文章是根据上一篇文章进行修改的,如果需要源码,请去上一篇文章中进行复制! 源码-传送门 cnpm i -...

网友评论

      本文标题:20.react-redux

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