Redux 结合 React,实现Counter (可与上一篇做对比)
先看效果
当点击 + 时,数值加1
当点击 - 时,数值减1
当点击 Increment if odd 时,会判断当前 store 里面的 state 是否不为偶数,当不为偶数则加1,否则没有效果
第一次点击,没效果
当加到1时候, 再次点击,则加1
当点击 Increment async 时,异步执行,定时器,执行一次 一秒后加1
文件总目录
代码示例
package.json (配置文件)
src/reducers/index.js
export default (state = 0, action) => {
switch(action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
src/components/Counter.js
import React, {
Component } from 'react'
import PropTypes from 'prop-types'
class Counter extends Component {
constructor(props) {
super(props)
this.incrementAsync = this.incrementAsync.bind(this);
this.incrementIfOdd = this.incrementIfOdd.bind(this);
}
incrementIfOdd() {
if(this.props.value % 2 !== 0) {
this.props.onIncrement()
}
}
incrementAsync() {
setTimeout(this.props.onIncrement, 1000)
}
render() {
const {
value, onIncrement, onDecrement } = this.props
return (
<p>
Clicked: {
value } times
{
' '}
<button onClick={
onIncrement}>
+
</button>
{
' '}
<button onClick={
onDecrement}>
-
</button>
{
' '}
<button onClick={
this.incrementIfOdd}>
Increment if odd
</button>
{
' '}
<button onClick={
this.incrementAsync}>
Increment async
</button>
</p>
)
}
}
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired
}
export default Counter
注意
这里使用了prop-types检测props数据类型
一、为什么使用prop-types
在多人开发时,当被人使用自己定义的组件时,有可能出现类型传错的情况,而在自己的组件上加上prop-types,他可以对父组件传来的props进行检查,假如父组件中想传递的是字符串类型‘3’,而传递了一个数字类型3,如果没有类型检查系统不会给与提示,但是有了类型检查以后,再控制台会给你一个类型传递错误的提示。这样在工作中可以快速找到错误
二、安装与引入
//安装
npm install prop-types --save
//引入
import PropTypes from 'prop-types';
三、可以检测的类型
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol
四、使用isRequired设置属性为必须传递的值
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired
}
src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import {
createStore } from 'redux'
import counter from './reducers'
import Counter from './components/Counter'
const store = createStore(counter)
const rootEl = document.getElementById('root')
const render = () => ReactDOM.render(
<Counter
value = {
store.getState()}
onIncrement = {
() => store.dispatch({
type: 'INCREMENT' })}
onDecrement = {
() => store.dispatch({
type: 'DECREMENT' })}
/>,
rootEl
)
render()
store.subscribe(render)
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redux Counter Example</title>
</head>
<body>
<div id="root"></div>
</body>
</html>