Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React使用Dva构建应用 #19

Open
Wscats opened this issue Feb 14, 2019 · 0 comments
Open

React使用Dva构建应用 #19

Wscats opened this issue Feb 14, 2019 · 0 comments

Comments

@Wscats
Copy link
Owner

Wscats commented Feb 14, 2019

安装

全局安装dva-cli脚手架,会应有一个新的dva命令,使用它来初始化一个新的dva项目,然后它会自动安装所需的依赖,然后进入该项目文件夹,然后执行npm start启动项目

npm install dva-cli -g
dva -v
dva new dva-quickstart
cd dva-quickstart
npm start

路由

routes目录下新建Products.jsx组件

import React from 'react';
// 是帮你连接组件和redux
import { connect } from 'dva';
// 这是dispatch和products是来自于props的方法,是connect后提供的
// {dispatch, products}等价于props.dispatch和props.products
const Products = ({ dispatch, products }) => {
  function handleDelete(id, e) {
    // 获取按钮传递的数据
    console.log(id, e)
    // 获取Model的state的数据
    console.log(products)
    dispatch({
      // 触发Model中的action方法
      type: 'products/delete',
      // 这里是传过去Model的数据
      payload: {
        name: "lemon",
        age: 18,
        skill: ['ps', 'css', 'js']
      },
    });
  }
  return (<div>
    <h2>Dva连接Redux的示例</h2>
    <button onClick={handleDelete.bind(this, 1)}>连接Model</button>
  </div>)
};

export default connect(({ products }) => ({
  products,
}))(Products);

在上面的路由组件中我们看到connect,由于dva提供了connect 方法,这个 connect就是react-reduxconnect方法,帮助我们建立组件和Model之间关系

然后添加路由信息到路由表,编辑router.js

import Products from './routes/Products';
<Route path="/products" exact component={Products} />

Model

可以使用Model来封装一个类似于react-redux的数据仓库,来交互组件之间的数据

models目录下新建products.js文件

export default {
  namespace: 'products',
  // state: {
  //   author: "wscats"
  // },
  state:{},//如果这里为空可以在index.js的dva()方法中初始化值
  reducers: {
    'delete'(state, {
      payload
    }) {
      // state是Model里面存放的state数据
      // payload是获取来自于Product.jsx组件的dispatch传过来的payload参数
      console.log("触发了redux", state, payload)
      // 这里是返回新的state数据
      return {
        ...state,
        ...payload
      }
    },
    // 可以存放多个action的方法
    add(state, {
      payload
    }) {

    }
  },
};
  • namespace 表示在全局 state 上的 key
  • state 是初始值,在这里是空数组
  • reducers 等同于 redux 里的 reducer,接收 action,同步更新 state

然后在index.js文件里面载入它

// 3. Model
app.model(require('./models/products').default);

如果已经在state里面初始化了数据,那就可以忽略下面这一步,但如果state没有定义值,可以在index.js中的dva()方法中初始化值

// 1. Initialize
const app = dva({
  initialState: {
    products: {
      author: "Eno Yao"
    }
  }
});
@Wscats Wscats changed the title React 使用Dva构建应用 React使用Dva构建应用 Feb 14, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant