您好,欢迎来到爱玩科技网。
搜索
您的当前位置:首页react基础react-redux

react基础react-redux

来源:爱玩科技网

1、引入react-redux,在模板渲染口,使用Provider提供store,只要在Provider中使用的组件都可以调用到store中的state状态

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import store from './store'
import { Provider } from 'react-redux'
ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

2、在要使用store的组件中使用connect连接组件,通过mapStateToProps映射state到组件的props上,和mapDispatchToProps

将action映射到props上,然后正常调用

import React, { Component } from 'react';
import TodoListUi from './components/TodoListUi'
import TodoListItem from './components/TodoListItem'
import { connect } from 'react-redux'
import {
  addInputValue,
  addListItem,
  delListItem,
} from "./store/actionCreators";
class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <TodoListUi
          text={this.props.inputValue}
          changeInputValue={this.props.changeInputValue}
          addListInputValue={this.props.addListInputValue}
        ></TodoListUi>
        {this.props.list.map((item, index) => {
          return (
            <TodoListItem
              key={index}
              context={item}
              order={index}
              delListItem={this.props.delListItem.bind(this, index)}
            ></TodoListItem>
          );
        })}
      </div>
    );
  }
}
const mapStateToProps = (state, ownProps) => {
  // 将state映射到props上
  return {
    inputValue: state.inputValue,
    list: state.list
  }
}
const mapDispatchToProps = (dispatch, ownProps) => {
  // 将action映射到props上
  return {
    changeInputValue: (data) => {
      // 改变input的内容
      dispatch(addInputValue(data))
    },
    addListInputValue: () => {
       // 改变input的内容
      dispatch(addListItem())
    },
    delListItem: (data) => {
      // 删除子项
      dispatch(delListItem(data))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- aiwanbo.com 版权所有 赣ICP备2024042808号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务