【Redux】「bindActionCreators」とは。使い方 Reduxドキュメント日本語訳

ReduxドキュメントのbindActionCreators

======================

bindActionCreators(actionCreators, dispatch)

同じキーを持つオブジェクトに、
その値をActionCreatorであるオブジェクトにして、
dispatchにラップされたすべてのActionCreatorを呼ぶので、
それらは直接実行できるようになります

通常はStoreインスタンス上のdispatchを直接呼ばなくてはなりません。
もしあなたがReactと一緒にReduxを使うなら、
それを直接呼べるようにreact-deduxもdispatch関数を提供します。

bindActionCreatorに対してのみの使用は、
Reduxが気づかない下のコンポーネントに多くのaction creatorを渡したい時や、
dispatchに渡したくない時、
Reduxがそれに対してstoreする時です。

便利なことに第一引数として一つの関数を渡すこともできますし、
返り値で関数を得られることもできます

Parameters

1. actionCreators (Function or Object)
返り値: An action creator, か action creatorを値に持つobject

2. dispatch (Function) : Storeインスタンス上で利用可能なdispatch関数

Returns

(関数かオブジェクト): 元のオブジェクトを模倣したオブジェクトで、対応するaction creatoreが返したactionを各関数がただちにdispatchingする

もしactionCreatorsとしての関数を渡したら、
一つの関数にもなる値を返します

Example

TodoActionCreators.js
[code language="javascript"]
export function addTodo(text) {
return {
type: 'ADD_TODO',
text
}
}

export function removeTodo(id) {
return {
type: 'REMOVE_TODO',
id
}
}
[/code]

SomeComponent.js
[code language="javascript"]
import { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

import * as TodoActionCreators from './TodoActionCreators'
console.log(TodoActionCreators)
// {
// addTodo: Function,
// removeTodo: Function
// }

class TodoListContainer extends Component {
componentDidMount() {
// Injected by react-redux:
let { dispatch } = this.props

// Note: これは動きません:
// TodoActionCreators.addTodo('Use Redux')

//あなたはただactionを作成する関数を呼んでいるだけです
//actionをdispatchもしなくてはいけません

// これは動きます
let action = TodoActionCreators.addTodo('Use Redux')
dispatch(action)
}

render() {
// Injected by react-redux:
let { todos, dispatch } = this.props

//これはbindActionCreatorsの良いユースケースです
// あなたはReduxが子コンポーネントを全く知らないようにしたいです。

let boundActionCreators = bindActionCreators(TodoActionCreators, dispatch)
console.log(boundActionCreators)
// {
// addTodo: Function,
// removeTodo: Function
// }

return (
<TodoList todos={todos}
{...boundActionCreators} />
)

// bindActionCreatorsの代りに渡すことです
// ただ子コンポーネントにdispatch関数を渡すだけです。
//action creatorsをimport、それらについて知っている必要がある

// return <TodoList todos={todos} dispatch={dispatch} />
}
}

export default connect(
state => ({ todos: state.todos })
)(TodoListContainer)

[/code]

Tips

・あなたは尋ねるかもしれない: どうして昔のFluxのようにaction creatorsをすぐにstorインスタンスに対してbindするの?
この問題はサーバー上でレンダーする必要があるAppでよく動かないためです。
ほとんどの場合、別のデータを準備することができるので、あなたはリクエスト毎に分けたStoreインスタンスを持ちたいでしょう。
でもそれは定義中にaction creatorsをバインドすることで、
すべてのリクエストに対して一つのstoreインスタンスで詰まってしまうことを意味します。

・もしES5を使うなら、 import * as 構文の代わりに require('./TodoActionCreators') を 第一引数としてbindActionCreatorsへ渡すことだけです。
それに対して気をつけることは actionCreators引数の値は関数ということだけです。
モジュールシステムは重要ではありません。

【React/Redux】このアラートが出てきたらすること/warning.js:36 Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>. See Counter > p > ... > div.

React x Reduxを使っていて、
下記のようなものがコンソールに出てきたら、

【React/Redux】このアラートが出てきたらすること/warning.js:36 Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>. See Counter > p > ... > div.
【React/Redux】このアラートが出てきたらすること/warning.js:36 Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>. See Counter > p > ... > div.

したのようにpで返している箇所ありませんか??

【React/Redux】このアラートが出てきたらすること/warning.js:36 Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>. See Counter > p > ... > div.
【React/Redux】このアラートが出てきたらすること/warning.js:36 Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>. See Counter > p > ... > div.

ブロック要素が必要ならdivにしてください。
お願いします。

【関連記事】
【React】Reactの動きを理解したい人の為の最小サンプル

【React入門】過去のREACT初心者の自分にpropsとstateの違いを簡単に説明してあげたい

【React × ECMAScript2015 × Flux】を手っ取り早く学びたい人の為にサンプル作ったよ【3の倍数と3が付くときだけ猫になるカウンター】

React × Flux × ECMAScript2015 LINE風チャット

他のReact記事

フロントエンド記事

GitHub

qiita

【React/Redux】Propsがread-onlyでEmpty Object。。connectとか疑った後,Container内のComponentが何も返してくれない時

エラーにもならないで、静かに訴えています。。

【React/Redux】Propsがread-onlyでEmpty Object。。connectとか疑った後,Container内のComponentが何も返してくれない時
【React/Redux】Propsがread-onlyでEmpty Object。。connectとか疑った後,Container内のComponentが何も返してくれない時

写真のようにaddOnで見ると、、Propsがread-onlyでEmpty Object。。connectとか疑った後,Container内のComponentが何も返してくれない時

【React/Redux】Propsがread-onlyでEmpty Object。。connectとか疑った後,Container内のComponentが何も返してくれない時
【React/Redux】Propsがread-onlyでEmpty Object。。connectとか疑った後,Container内のComponentが何も返してくれない時

コンポーネントの最初の文字が小文字だった。。

ではーーーー

【Redux】これハマった。。invariant.js:38 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

ヒントもうちょっと欲しい。。って思いながら、、ハマった箇所。

2つの可能性があります。
①export, importを間違えている可能性
②setState内の記述が誤っている可能性
例えば
this.setState({
value: this.state - 1;
})
こう書いちゃっているとか
正しくは、、
this.setState({
value: this.state - 1
})

今回は①の場合、、

【Redux】これハマった。。invariant.js:38 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
【Redux】これハマった。。invariant.js:38 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

componentはElementを返さなくてはいけませんよっ、ただundefinedですよ。
っていうことだと思うので、ひたすらContainerやComponentのrenderがreturnしているか
をチェックした。

react-reduxからimportにしてないケース

【Redux】これハマった。。invariant.js:38 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
【Redux】これハマった。。invariant.js:38 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

 

外部に公開していないケース

app_js_-_react-sample_-____react-sample_

 

ではーーーー

【webpack】webpackDevMiddleware とは

webpackDevMidleware -ドキュメント-

webpackDevMiddleware はデータ構造領域に接続するミドルウェに対しての小さなミドルウェアです。
メモリーの静的ファイルをコンパイルしたりそれらを受け取る際に使用します。

コンパイルがwebpackのアセットを受け取るリクエスト毎に実行している際、私たちが安定したbundleを持つまでブロックされます。

2つのモードを使う事ができます。

・watch mode (デフォルト) コンパイラーはファイル変更で再コンパイルします。
・lazy mode コンパイラはエントリーポイントへのリクエスト毎にコンパイルします。

API

[code]
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpack = require("webpack");

var compiler = webpack({
// configuration
output: { path: '/' }
});

app.use(webpackDevMiddleware(compiler, {
// オプション
}));
//app.useはexpressで利用するミドルウェアの関数を渡す
//app.use([path, ] middlewareFunc)
//pathが省略された場合'/'。path有りの場合そのpathに対してミドルウェア(<a href="https://expressjs.com/en/guide/using-middleware.html">ミドルウェアの説明</a>)を使う
//ミドルウェアの関数シグネチャは function(req, res, next)
//ミドルウエアはファクトリ関数(関数をreturnする関数)を使って生成するものが多い。この例の場合、webpackDevMiddleware関数はfunction(req, res, next)というシグネチャを持った関数を返す

[/code]

オプション
noInfo
警告とエラーのみコンソール出力する
Default: false

quiet
何もコンソールに出力しない
Default: false

lazy
lazyモードに切り替える
Default: false

filename
lazyモードでコンパイルされるトリガーすべきリクエストに切り替える
多くの場合webpack設定オプション「output.filename」と等価です。

watchOptions.aggregateTimeout
最初の変更後の再ビルドを遅らせる
値はmsです 1000ms  = 1秒
Default: 300

watchOptions.poll
true: use polling (pollingを使う)詳しい設定方法(Document)
number: use polling with specified interval (詳細な間隔で使う)
Default: undefined

publicPath (required)
サーバーに対してのbindしたミドルウェアへのパス
多くの場合 これはwebpack設定のoutput.publicPathと等価です。

headers
独自ハンドラを追加します
例 { "X-Custom-Header": "yes" }

stats
状態に対してのオプション出力
node.js API.を参照してください

middleware.invalidate()
手動でコンパイルを無効にします。
コンパイル変更時の内容を有効にする

middleware.fileSystem
メモリ上のコンパイルされたデータにアクセスできる可読のファイルシステム

【Redux】Uncaught Error: Objects are not valid as a React child (found: object with keys {counterReducer, inputReducer}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Component`.(…)

【Redux】Uncaught Error: Objects are not valid as a React child (found: object with keys {counterReducer, inputReducer}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Component`.(…)
【Redux】Uncaught Error: Objects are not valid as a React child (found: object with keys {counterReducer, inputReducer}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Component`.(…)

値の型が違う風に渡ってきている。該当の`Component`のrenderメソッド内を確認してみて!
render関数のなかでreturnする前にconsole.log()でそのなかで使っている変数調べたら
propTypesでnumberにしていたのにObjectが渡ってきたよ。

%e3%82%b9%e3%82%af%e3%83%aa%e3%83%bc%e3%83%b3%e3%82%b7%e3%83%a7%e3%83%83%e3%83%88_2016-10-22_14_25_41_png

%e3%82%b9%e3%82%af%e3%83%aa%e3%83%bc%e3%83%b3%e3%82%b7%e3%83%a7%e3%83%83%e3%83%88-2016-10-22-14-25-41

【Redux】これが出たら疑う箇所:Uncaught Error: Objects are not valid as a React child (found: object with keys {counterReducer, inputReducer}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Component`.(…)
【Redux】これが出たら疑う箇所:Uncaught Error: Objects are not valid as a React child (found: object with keys {counterReducer, inputReducer}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Component`.(…)

みてみると

【Redux】これが出たら疑う箇所:Uncaught Error: Objects are not valid as a React child (found: object with keys {counterReducer, inputReducer}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Component`.(…)
【Redux】これが出たら疑う箇所:Uncaught Error: Objects are not valid as a React child (found: object with keys {counterReducer, inputReducer}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Component`.(…)

【Redux/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」

【Redux/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」
【Redux/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」

Uncaught TypeError: (0 , _redux.combinReducers) is not a function
そのreducer、関数ではないよ。やだよ関数じゃないと。と言われています。

呼び出し側と呼び出し元の不一致のはず。
not mutch called flie and call file

罰としてドキュメント読む。
try to read document of combineReducers

Arguments

reducers (Object): An object whose values correspond to different reducing functions that need to be combined into one. See the notes below for some rules every passed reducer must follow.

引数:reducerオブジェクト 。値は一つに結合される必要がある異なるreducer関数

Earlier documentation suggested the use of the ES6 import * as reducers syntax to obtain the reducers object. This was the source of a lot of confusion, which is why we now recommend exporting a single reducer obtained using combineReducers() from reducers/index.js instead. An example is included below.

早期のドキュメントではreducersオブジェクトを取得するためにES6 import * as reducers構文の使用を提案してました。
これは多くの混乱の元です。わたしたちは 代わりに、combineReducers()を使ってreducers/index.jsから取得する一つのreducerとしてexportすることをお勧めします。

Returns

(Function): A reducer that invokes every reducer inside the reducers object, and constructs a state object with the same shape.

返り値:関数
reducersオブジェクト内で同じ形状を持ったstateオブジェクトをもつ、reducer毎に実行するreducer

//reducer/index.js

【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」
【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」

other file is ..

//reducer/counterReducer.js

【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」
【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」

combinReducerを使っているファイルでこのようにしてみる。
in file which used function of combineReducer,
write console.log()

console.log(inputReducer, counterReducer, combinReducers);

【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」
【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」

undefined x 3 なので 読み込まれていない
see undefined *3

ここに習って
see document redux combineReducers
https://redux.js.org/docs/api/combineReducers.html

それぞれのファイル間でのexport import 書き直す
fix file like this

【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」
【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」
【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」
【Redex/combineReducers】これが出たら真っ先に疑う箇所「Uncaught TypeError: (0 , _redux.combinReducers) is not a function」

export default function fafa () {}

情けない。

今度は読み込まれた

%e3%82%b9%e3%82%af%e3%83%aa%e3%83%bc%e3%83%b3%e3%82%b7%e3%83%a7%e3%83%83%e3%83%88-2016-10-22-12-54-01

combinReducersだけまだ読み込まれていない(undefined)
なぜなら綴りが違うから(this is typo)
情けない。

fix
combinReducers

combineReducers

エラーは解消されて幸せ。

はい。つぎつぎ

【関連記事】
【React】Reactの動きを理解したい人の為の最小サンプル

【React入門】過去のREACT初心者の自分にpropsとstateの違いを簡単に説明してあげたい

【React × ECMAScript2015 × Flux】を手っ取り早く学びたい人の為にサンプル作ったよ【3の倍数と3が付くときだけ猫になるカウンター】

React × Flux × ECMAScript2015 LINE風チャット

他のReact記事

フロントエンド記事

GitHub

qiita

【海外記事】NPM vs Yarn Cheat Sheet 日本語訳(npm と yarnの違い)

%e3%82%b9%e3%82%af%e3%83%aa%e3%83%bc%e3%83%b3%e3%82%b7%e3%83%a7%e3%83%83%e3%83%88-2016-10-21-20-27-22
あなたはyarnという新しいJavaScriptパッケージマネージャーを聞いた事あって、その使い方を知りたい
でしょう。
NPMを知っているならもうほとんどの部分は設定されています。

ここではスイッチする際の注意点をお伝えします。

Cheat Sheet — What you need to know
知っておくべき事

・npm install === yarn

インストールはデフォルトの振る舞いです。

・npm install taco --save === yarn add taco

Tacoパッケージはすぐさまpackage.jsonに保存されます。

・npm uninstall taco --save === yarn remove taco

--save は「npm config set save true」によってNPMのなかでデフォルトとされています。
ただし、これは大抵の開発者にたいして明示的にされていません。
package.jsonからの追加と削除はYarnではデフォルトです。

・npm install taco --save-dev === yarn add taco --dev

・npm update --save === yarn upgrade

アップデート対アップグレードがあります、それらは正確には
それが何をしているか。
バージョン番号が動き、アップグレードは何か起こる!

注意 npm update --save は3.11で壊れているようです。

・npm install taco@latest --save === yarn add taco

・npm install taco --global === yarn global add taco

あなたがすでにyarnについて知っています

パッケージは同じNPMレジストリー上のものです
yarnは基本的にNPM構造とレジストリーが同じ新しいインストーラーです。

・npm init === yarn init

・npm link === yarn link

・npm outdated === yarn outdated

・npm publish === yarn publish

・npm run === yarn run

・npm cache clean === yarn cache clean

・npm login === yarn login (and logout)

・npm test === yarn test

yarnはNPMが持っていない事を持っています

・yarn clean

警告を出すアイテムを飛ばします

・yarn licenses ls

あなたの依存のライセンスを覗き見る事を可能にします

・yarn why taco

tacoパッケージがインストールされている理由、他のパッケージがそれに依存する詳細をみる

・早いです

※たしかにインストールが早い

・yarn lockfileで自動的なシュリンクラップ

依存するバージョンを固定することができる

ここから脱線して調べた事↓
※npm shrinkwrapとの違い(npm shrinkwrapとはなにかはここ)
・デフォルトで生成されるので簡単に利用できる
・各モジュールがソートされており構成管理が容易ということ
(より依存モジュールのバージョン記載のファイルが見やすく、それはデフォルトで生成されるようになったってことですね。)

・Security-centric designです

(後で調べる)

NPMができてyarnがもっていないこと
・npm xmas === **NO EQUIVALENT**
・npm visnup === **NO EQUIVALENT**

ちょっと深掘りしてみますーー

ではーーー

わたしもみている | rollup.js | react_speed_cording | Babel で ES7 Async/Await を試してみた |

React_Speed_Cording
webpackのバージョンが2では動かないっていうのが気になる。。

英語動画
リスニングしやすい動画。。

Taming the asynchronous beast with ES7
そろそろそこらへんもまとめたい。。

今更ながら Babel で ES7 Async/Await を試してみた
ここも。。

rollup.js (next-generation JavaScript module bundler)
Webpack2との違いが知りたい。。

Beginner’s guide to Webpack
やさしい。。

JavaScriptの仕様を書いている人
フォローしてた。。

JavaScriptの仕様書の経緯
これで追っているんすね。。毎年6月にECMAScript20XXとしてリリースするんすね。
2016はArray.include()と2**2 === 2 * 2 * 2だけ
2017はasync/await、Object.values, Object.entries(),Object.getOwnPropertyDescriptorsとか

【Angular2入門】TypeScriptをコンパイルからのWatchifyでファイル結合、ブラウザで動作確認するところまで - Gulpで作るwebフロントエンド開発環境
Gulpか。。Webpackがいいな。。

ECMAScript® 2017 Language Specification
冬ですね。そろそろ。。

You Don't Know ES Modules
defaultをdefで参照できるのか。。

東京Node学園
ここチェックしておけばいいのか。。

JSConf Iceland 2016
アイスランドであったんすね。。

フロントエンドエンジニアが暇なときにやると良いかもしれないこと
多いな。。

英語の「不定詞」|3つの用法を簡単に5分でマスターする!
丁寧な記事。

関係代名詞の「which」の3つの使い方を簡単マスター!
いいね。

WHAT ARE LOADERS?
ここらへんをもっと知ればもっと便利になる。。

他の「わたしもみてる記事」

【Webpack】ERROR in multi html Module not found: Error: Cannot resolve module 'file' in

ERROR in multi html
Module not found: Error: Cannot resolve module 'file' in /Users/[username]/[repository]/[projectName]/src
@ multi html

confirm Error
type this one
webpack --display-error-details

see console

【Webpack】ERROR in multi html Module not found: Error: Cannot resolve module 'file' in
【Webpack】ERROR in multi html Module not found: Error: Cannot resolve module 'file' in

try npm install file

Enable USB debugging on your Android device
AndroidデバッグをMacPCでやる方法のDocument

ハードウェア端末上でアプリを実行する
Android実機でUSB繋いでもDeveloper Optionが表示されない問題はこれだった。7回タップするって。。

GPUアクセラレーションとposition: relativeによるレイヤー生成について
position relative内でanimation要素があるとそのレイヤー全体がリペインされるのか。。

Webサイトのパフォーマンス改善を行うためにGPU処理を取り入れてみた
でそれを解決させる1つに「backface-visibility: hidden;」ってのもあるんだ。。

他の「わたしもみてる記事」

【Error】node-sassが怪しい | fs.js:856 return binding.readdir(pathModule._makeLong(path));でたら

久しぶりに動かしたプロジェクトでgulp叩いたらエラー出てた。
fs.js:856 return binding.readdir(pathModule._makeLong(path));
スタックトレース追っていったらnode-sassとかから出ているみたい。

ここ参考に、
やっていることはインストールしなおしているようなので、依存関係おかしくなっているのかな。。

npm i -D node-sass

tslintもエラー出てたら
npm i -D tslint

動いた。
これから腕まくりします。

でわーーーーーーーー