美文网首页前端开发 从基础到框架
react项目教程 装饰器写法 vscode装饰器报错设置(用r

react项目教程 装饰器写法 vscode装饰器报错设置(用r

作者: 不7而遇_ | 来源:发表于2018-12-01 15:41 被阅读81次

    要实现 头部 页面不同数据渲染 首先创建一个头部组件
    在components 文件夹中在创建一个Header 文件夹 并创建一个index.js
    为了用到store中的数据 在index 页面我们要引入connect
    connect()()的正常写法要有两个括号 现在可以配置一个更加简单的装饰器方式

    npm install --save-dev babel-plugin-transform-decorators-legacy
    并在package.json 中做如下配置

     "plugins": [
          "transform-decorators-legacy"
    ]
    

    这样header中要写用到connect 就可以写成
    此时this.props.title 就可以取到 rudecer 中show.js 的initState 中的title 的值界面的 Header也会渲染 title 的值
    在connect 第一个参数中传入 mapState 是为了实时监控mapState 的数据,当数据改动时全局都会修改

    import React, { Component } from 'react'
    import { connect } from 'react-redux'
    import {NavBar ,Icon} from 'antd-mobile'
    const mapState =(state) => {
      return {
        title : state.show.title
      }
    }
    
    @connect(mapState)
    export default class Header extends Component {
      render() {
    console.log(this.props.title)
    
        return (
          <div>
            <NavBar
          mode="light"
          icon={<Icon type="left" />}
          onLeftClick={() => console.log('onLeftClick')}
          rightContent={[
            <Icon key="0" type="search" style={{ marginRight: '16px' }} />,
            <Icon key="1" type="ellipsis" />,
          ]}
        >{this.props.title}</NavBar>
          </div>
        )
      }
    }
    

    这里的vscode 可能会报错 但是不影响编译 如果想要去掉 编译错误 可以更改vscode设置
    在settings 中找到 Workspace Settings 中找到

    "javascript.implicitProjectConfig.experimentalDecorators": false  
    

    修改为

    "javascript.implicitProjectConfig.experimentalDecorators": true
    

    现在要根据理由来判断header的显示内容 我们就需要用到中间件 redux-thunk 来写action
    现在我们可以创建一个actions 的文件夹用来保存动作。
    在actions
    现在我们需要在actions 中创建一个actionType.js 文件 用来保存所有的操作名称 如我们现在需要动态更改tabbar 则 actionType.js 中为

    export const CHANGE_TITLE = "CHANGE_TITLE"
    

    然后同时在action中创建 show.js 与 reducer中的show.js对应
    在其中引入 actionType

    import  * as actionType  from './actionType'
    export const changeTitle  = (title) => {
      return {
        type: actionType.CHANGE_TITLE,
        title
      }
    }
    

    目的是用来规定changeTitle 这个方名字 需要传递一个对象,第一个熟

    同时我们需要在 reducer 中的 show.js 中引入 actionType
    此时mall 里 做这样的操作 header 就被修改里
    这里的 null 意识是我们不需要传递数据 只需要方法,

    import React, { Component } from 'react'
    import { connect } from 'react-redux'
    import { changeTitle } from '../../actions/show'
    @connect(null, { changeTitle })
    export default class Mall extends Component {
     componentDidMount() {
       this.props.changeTitle('Mall')
     }
     render() {
       console.log(this.props)
       return (
         <div>
           mall
         </div>
       )
     }
    }
    

    那么我们需要理清一下 react-redux 工作的流程。

    https://www.jianshu.com/p/5d2b7bcec8e9

    相关文章

      网友评论

        本文标题:react项目教程 装饰器写法 vscode装饰器报错设置(用r

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