再谈React-Native With Redux [转载]

原文

redux三大原则

首先,我们明确一点:redux的核心思想就是FLux架构,单向数据流。

单一数据源

在redux中,所有的state最后都会被combine起来,变为一个大的state树,这个state树只存在于唯一的一个store中。这么做的好处是开发和调试都变得很方便,也很好理解。

state只读

改变state唯一的办法就是通过触发action,别无他法。这么做非常纯粹,确保没其他副作用,state不会被任意修改。

纯函数修改state

想要修改state,在action被触发之后,需要编写reducer来进行修改,reducer只是一些纯函数,它会接受到action和state,返回全新的state。
继续阅读“再谈React-Native With Redux [转载]”

Redux Example



react-pxq

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'

// React component
class Counter extends Component {
  render() {
    const { value, onIncreaseClick } = this.props
    return (
      <div>
        <span>{value}</span>
        <button onClick={onIncreaseClick}>Increase</button>
      </div>
    )
  }
}

Counter.propTypes = {
  value: PropTypes.number.isRequired,
  onIncreaseClick: PropTypes.func.isRequired
}

// Action
const increaseAction = { type: 'increase' }

// Reducer
function counter(state = { count: 0 }, action) {
  const count = state.count
  switch (action.type) {
    case 'increase':
      return { count: count + 1 }
    default:
      return state
  }
}

// Store
const store = createStore(counter)

// Map Redux state to component props
function mapStateToProps(state) {
  return {
    value: state.count
  }
}

// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
  return {
    onIncreaseClick: () => dispatch(increaseAction)
  }
}

// Connected Component
const App = connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter)

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)