dva中redux读取和修改数据基本操作

1.models/goodList.js文件

export default {
  namespace: "goodList",
  state: {
    goodsList: [
      {
        type: "小说",
        name: "莫泊桑小说",
      },
      {
        type: "历史",
        name: "秦皇治国史册",
      },
      {
        type: "文学",
        name: "朱自清散文集",
      },
    ],
  },
  reducers: {
    updateList(state, action) {
      const newState = JSON.parse(JSON.stringify(state));
      newState.goodsList.push(action.payload);
      return newState;
    },
  },
};

2.将models/goodList.js引入入口文件index.js

app.model(require("./models/goodList").default);

3.页面中使用

import { Component } from "react";
import GoodList from "../../components/goodsList";
import { connect } from "dva";

class Goods extends Component {
  render() {
    const { list, dispatch } = this.props;
    return (
      <>
        
      
    );
  }
}

//访问redux里面state数据
//将state中的goodsList赋值props属性list
const mapStateToProps = (state) => {
  return {
    list: state.goodList.goodsList,
  };
};

export default connect(mapStateToProps)(Goods);

4.子组件中接收和修改state数据

import { Component } from "react";
export default class GoodList extends Component {
//子组件操作dispatch修改reducers中方法updateList, reducers修改state中的数据状态 返回最新的state
  addDataList = () => {
    this.props.dispatch({
      type: "goodList/updateList",
      payload: { type: "外国著作", name: "1001夜" },
    });
  };

  render() {
    const { goodsList } = this.props;
    return (
      <>
        {goodsList.map((item, index) => {
          return (
            
  • {item.type}
  • {item.name}
); })} ); } }

你可能感兴趣的:(react,react.js)