【问题标题】:Building React/Redux Application构建 React/Redux 应用程序
【发布时间】:2016-06-11 05:36:06
【问题描述】:

使用 redux 和 react 制作单页应用程序,首先要做的是什么? 先用redux创建我的state的逻辑还是让所有组件先反应?

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    可能要做的第一件事是建立您的减速器功能。 这是一个例子。我正在使用 ES6 示例。

    const INCREMENT = 'redux-example/counter/INCREMENT';
    
    const initialState = {
      count: 0
    };
    
    export default function reducer(state = initialState, action = {}) {
      switch (action.type) {
        case INCREMENT:
          const {count} = state;
          return {
            count: count + 1
          };
        default:
          return state;
      }
    }
    
    export function increment() {
      return {
        type: INCREMENT
      };
    }
    

    然后你必须创建一个组件:

    import React, {Component, PropTypes} from 'react';
    import {connectMultireducer} from 'multireducer';
    import {increment} from 'redux/modules/counter';
    
    @connectMultireducer(
      (key, state) => ({count: state.multireducer[key].count}),
      {increment}
    )
    export default class CounterButton extends Component {
      static propTypes = {
        count: PropTypes.number,
        increment: PropTypes.func.isRequired,
        className: PropTypes.string
      }
    
      props = {
        className: ''
      }
    
      render() {
        const {count, increment} = this.props; // eslint-disable-line no-shadow
        let {className} = this.props;
        className += ' btn btn-default';
        return (
          <button className={className} onClick={increment}>
            You have clicked me {count} time{count === 1 ? '' : 's'}.
          </button>
        );
      }
    }
    

    在您的组件中,您可以将 reducer 状态和操作连接到您的组件,然后将它们包装到容器中并将它们链接到 HTML。

    希望这会有所帮助。

    【讨论】:

    • 你好,我一直在学习 es2015,@(操作员?)对我来说有点新意,请解释一下?
    • @ 是装饰器,可让您编写更少的代码来进行 redux 连接。这是一个链接,可以更详细地解释它。 stackoverflow.com/questions/32646920/…
    【解决方案2】:

    我认为这在很大程度上取决于您是否更好地了解您的数据或您的 UI。我会写出一个容器组件,然后将所有数据作为状态传递给它,然后将其映射到道具。从那里你可以决定哪些组件需要状态树的哪一部分。然后,您可以根据数据进行推理组件设计。

    这是我草拟的一个简单示例:https://github.com/matthewkturner/redux-simple-boilerplate

    【讨论】:

    • 嗯,我认为理解 UI 更好。然后您可以立即了解数据。虽然这只是我的看法,因为我只是一个纯粹的前端开发人员,对后端(php)知之甚少
    • 站在专业人士的立场上(没有人可能会看到非专业人士哈哈),他们通常会做什么?我找不到涵盖两者的好教程/示例。
    【解决方案3】:

    如果先做所有组件或先做所有状态,你会犯错。

    只需从 1 个组件开始并将其连接到 redux。不要编写还没有必要的状态或组件。

    最好从必要的代码开始,如果需要更改,则修改/重构该代码。

    当您的假设不正确并且您必须重写预先编写的组件时,预优化会很痛苦。在项目期间,您总是会发现更好的方法来做事,因此您当时拥有的组件和/或减速器越多,您的返工就越多。

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 2019-02-07
      • 2016-03-12
      • 1970-01-01
      • 2016-04-30
      相关资源
      最近更新 更多