Reduxは、Reactを組み合わせてCounterを実装します(前の記事と比較できます)
まず効果を見て
+をクリックすると、値が1ずつ増加します
をクリックすると、値が1減少します
Increment if oddをクリックすると、現在のストアの状態が偶数でないかどうかを判断し、偶数でない場合は1を加算します。それ以外の場合は効果がありません。
最初のクリック、影響なし
1に追加されたら、もう一度クリックしてから1を追加します。
[非同期に増分]をクリックすると、非同期で実行され、タイマーが1回実行され、1秒後に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データ型を検出します
1.プロップタイプを使用する理由
マルチパーソン開発では、誰かが自己定義コンポーネントを使用すると、タイプが誤って渡される可能性があります。コンポーネントにプロップタイプを追加すると、親コンポーネントからプロップをチェックできます。親コンポーネントで渡したいのは、文字列タイプ「3」で、数値タイプ3が渡されます。タイプチェックがない場合、システムはプロンプトを表示しませんが、タイプチェックの後、コンソールはタイプ転送エラーを表示しますチップ。このようにして、職場でエラーをすばやく見つけることができます
2、インストールと紹介
//安装
npm install prop-types --save
//引入
import PropTypes from 'prop-types';
3.検出できる種類
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol
4、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>