美文网首页
react-redux

react-redux

作者: 未路过 | 来源:发表于2022-10-29 12:31 被阅读0次

我们需要给count组件外面套一层壳子,
count组件自身不用再操作sotre.dispatch和store.getState()了,
而且不用discribe来更新页面。


react-redux.PNG

父组件从标签那边获得store对象,然后再通过connect方法
把需要用的东西传递给真实store组件的props,子组件所用的操作都是从props里面拿。
npm i react-redux
1.创建父组件
这个时候store.js和reducer都是不动的。
就是以前count直接使用sotre,现在变成父容器直接使用store了。
让父组件接受store

import React, { Component } from "react";
import CountContainer from "./components/Count";
import Person from "./components/Person";
import countStore from "./store/modules/count";
export default class App extends Component {
  render() {
    return (
      <div>
        <CountContainer store={countStore}> </CountContainer>
        <Person></Person>
      </div>
    );
  }
}

父组件

import React, { Component } from "react";
import { connect } from "react-redux";

class Count extends Component {
  increment = () => {};
  decrement = () => {};
  asyncIncrement = () => {};
  render() {
    return (
      <div>
        <div>当前Count:0</div>
        <button onClick={this.increment}>点我加1</button>
        <button onClick={this.decrement}>点我减1</button>
        <button onClick={this.asyncIncrement}>点我异步加1</button>
        <hr />
      </div>
    );
  }
}

const CountContainer = connect(fn1, fn2)(Count);

export default CountContainer;

然后就要考虑fn1,和fn2怎么写了
fn1是一个回调函数,返回store中的数据 mapStateToProps
fn2是一个回调函数,返回的是dispatch里面的action
mapDispatchToProps
组件调用这个方法,就相当于store.dispatch(action)

increment: (number) => dispatch(incrementAction(number)),
import React, { Component } from "react";
import { connect } from "react-redux";
import {
  incrementAction,
  decrementAction,
  asyncIncrementAction,
} from "../store/modules/count/createActions";
class Count extends Component {
  increment = () => {
    this.props.increment(1);
  };
  decrement = () => {
    this.props.decrement(1);
  };
  asyncIncrement = () => {
    this.props.asyncIncrement(1);
  };
  render() {
    return (
      <div>
        <div>当前Count:{this.props.count}</div>
        <button onClick={this.increment}>点我加1</button>
        <button onClick={this.decrement}>点我减1</button>
        <button onClick={this.asyncIncrement}>点我异步加1</button>
        <hr />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return { count: state };
}

function mapDispatchToProps(dispatch) {
  return {
    increment: (number) => dispatch(incrementAction(number)),
    decrement: (number) => dispatch(decrementAction(number)),
    asyncIncrement: (number) => dispatch(asyncIncrementAction(number)),
  };
}

const CountContainer = connect(mapStateToProps, mapDispatchToProps)(Count);

export default CountContainer;

这样就完成了,再完全不动sotre.js和reducer的情况下,我们就实现了父容器和子组件的交流。

接下来就是要解决
有多个组件的问题
这个时候再建造一个person出来
创建一个person的组件和父容器,单独实现redux。

1.先创建person的store

import { legacy_createStore as createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import personReducer from "./reducer";

const personStore = createStore(personReducer, applyMiddleware(thunk));

export default personStore;

2.创建reducer

import { ADD_PERSON } from "./constant";
const initialState = [{ name: "default", age: 18 }];

function personReducer(preState = initialState, action) {
  const { type, data } = action;
  console.log("person, reducer", preState, type);
  switch (type) {
    case ADD_PERSON:
      return [...preState, data];

    default:
      return preState;
  }
}

export default personReducer;

3.创建父容器并且给父容器引入store

import React, { Component } from "react";
import { connect } from "react-redux";
import { addPerson } from "../store/modules/person/createActions";
class Person extends Component {
  add = () => {
    const name = this.nameNode.value;
    const age = this.ageNode.value;
    console.log(name);
    this.props.addPerson(name, age);
  };
  render() {
    return (
      <div>
        <input
          type="text"
          placeholder="name"
          ref={(e) => {
            this.nameNode = e;
          }}
        />
        <input type="text" placeholder="age" ref={(e) => (this.ageNode = e)} />
        <button onClick={this.add}>add</button>
        <div>
          <ul>
            {this.props.personList.map((item) => {
              return (
                <li key={item.name}>
                  {item.name}- {item.age}
                </li>
              );
            })}
          </ul>
        </div>
      </div>
    );
  }
}
function mapStateToProps(state) {
  return { personList: state };
}

function mapDispatchToProps(dispatch) {
  return {
    addPerson: (name, age) => {
      dispatch(addPerson(name, age));
    },
  };
}
const PersonContainer = connect(mapStateToProps, mapDispatchToProps)(Person);

export default PersonContainer;
import React, { Component } from "react";
import CountContainer from "./components/Count";
import PersonContainer from "./components/Person";
import countStore from "./store/modules/count";
import PersonStore from "./store/modules/person";
export default class App extends Component {
  render() {
    return (
      <div>
        <CountContainer store={countStore}> </CountContainer>
        <PersonContainer store={PersonStore}></PersonContainer>
      </div>
    );
  }
}

以上就是
count组件-count父容器-coucount组件-count父容器-personStore(personReducer)-personStore-(personReducer)

我们想把store放到一起。
这个时候要使用redux
以前: 0
以前:[{ name: "default", age: 18 }];
两个是分开de
现在redux
count:0
person:[{ name: "default", age: 18 }];
这个样子

废弃掉以前的coutStore和personStore

import {
  legacy_createStore as createStore,
  applyMiddleware,
  combineReducers,
} from "redux";

import thunk from "redux-thunk";
import countReducer from "./modules/count/reducer";
import personReducer from "./modules/person/reducer";

const allReducer = combineReducers({
  count: countReducer,
  person: personReducer,
});
export default createStore(allReducer, applyMiddleware(thunk));

app.js
···jsimport React, { Component } from "react";
import CountContainer from "./components/Count";
import PersonContainer from "./components/Person";

export default class App extends Component {
render() {
return (
<div>
<CountContainer> </CountContainer>
<PersonContainer></PersonContainer>
</div>
);
}
}

```js
import React, { Component } from "react";
import { connect } from "react-redux";
import { addPerson } from "../store/modules/person/createActions";
class Person extends Component {
  add = () => {
    const name = this.nameNode.value;
    const age = this.ageNode.value;
    console.log(name);
    this.props.addPerson(name, age);
  };
  render() {
    console.log("-------------");
    console.log(this.props);
    return (
      <div>
        <input
          type="text"
          placeholder="name"
          ref={(e) => {
            this.nameNode = e;
          }}
        />
        <input type="text" placeholder="age" ref={(e) => (this.ageNode = e)} />
        <button onClick={this.add}>add</button>
        <div>
          <ul>
            {this.props.personList.map((item) => {
              return (
                <li key={item.name}>
                  {item.name}- {item.age}
                </li>
              );
            })}
          </ul>
        </div>
      </div>
    );
  }
}
function mapStateToProps(state) {
  console.log(state);
  return { personList: state.person };
}

function mapDispatchToProps(dispatch) {
  return {
    addPerson: (name, age) => {
      dispatch(addPerson(name, age));
    },
  };
}
const PersonContainer = connect(mapStateToProps, mapDispatchToProps)(Person);

export default PersonContainer;

count

import React, { Component } from "react";
import { connect } from "react-redux";
import {
  incrementAction,
  decrementAction,
  asyncIncrementAction,
} from "../store/modules/count/createActions";
class Count extends Component {
  increment = () => {
    this.props.increment(1);
  };
  decrement = () => {
    this.props.decrement(1);
  };
  asyncIncrement = () => {
    this.props.asyncIncrement(1);
  };
  render() {
    return (
      <div>
        <div>当前Count:{this.props.count}</div>
        <button onClick={this.increment}>点我加1</button>
        <button onClick={this.decrement}>点我减1</button>
        <button onClick={this.asyncIncrement}>点我异步加1</button>
        <hr />
      </div>
    );
  }
}

function mapStateToProps(state) {
  console.log(state);
  return { count: state.count };
}

function mapDispatchToProps(dispatch) {
  return {
    increment: (number) => dispatch(incrementAction(number)),
    decrement: (number) => dispatch(decrementAction(number)),
    asyncIncrement: (number) => dispatch(asyncIncrementAction(number)),
  };
}

const CountContainer = connect(mapStateToProps, mapDispatchToProps)(Count);

export default CountContainer;

可以在count中使用person的数据


function mapStateToProps(state) {
  console.log(state);
  return { count: state.count, personList: state.person };
}

因为这个state是全部的state,有全部的redux里面的数据

相关文章

网友评论

      本文标题:react-redux

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