react dva 怎么更改state

文章2022-08-0827 人已阅来源:网络

react dva更改state的方法:1、创建DvaState.js和dvaState.js文件;2、输入代码为“import React from 'react';import { connect } from ...}”即可。

本文操作环境:Windows7系统、react17.0.1、Dell G3。

react dva 怎么更改state?

react dva框架 点击修改state的值 类似react中的this.state和this.setState()

先展示下

点击改变前state的值

点击改变后state的值的变化

首先创建者两个文件

routes目录下的DvaState.js

import React from 'react';import { connect } from 'dva';import { Link } from 'dva/router';let count  = 0const DvaState = ({
      dispatch,      dvaState,      }) => {  const {dataList} = dvaState
  console.log(dataList)
  console.log(dvaState)  const handleChangeState = () => {
    dispatch({      type:'dvaState/changeState',      payload:{        dataList:[
          {            list1: count++,            list2: 'list22',            list3: 'list33'          },          {            list2:'111'          }
        ]
      }
    })
  }  return (    <p>      <h2>dvaState</h2>      <h2>{dataList[0].list1}</h2>      <button onClick={handleChangeState}>改变state</button>    </p>  );};export default connect(({ dvaState }) => ({
  dvaState
}))(DvaState);

models 目录下的 dvaState.js

export default {  namespace: 'dvaState',  state: {    dataList:[
      {        list1:'a',        list2:'c',      }
    ]
},  subscriptions: {    setup({ dispatch, history }) {

    },  },  effects: {

  },  reducers: {    changeState(state, {payload}) {      return {...state, ...payload}
    }
  },};

以上就是react dva 怎么更改state的详细内容!