これはすべてあなたが達成しようとしているものによって決まります。一見すると2つの選択肢があります。 1つは子コンポーネントを作成し、2つは作成します:reduxはすべての子コンポーネント間に特異状態を提供するため、reduxを使用します。
最初のオプション:
export default class parentClass extends Component {
state = {
param1: "hello".
};
render() {
return (
<Child param1={this.state.param1}/>
);
}
}
class Child extends Component {
render() {
console.log(this.props.param1);
return (
<h1>{this.props.param1}</h1>
);
}
}
今すぐ上記の子コンポーネントはprops.param1
は、それが機能をレンダリング親から渡された小道具から定義されています。
上記は機能しますが、私はあなたが '共通の'機能セットを確立しようとしているのを見ることができます。オプション2の並べ替えは、あなたのアプリケーション/プロジェクトの特異状態を作成することによって、その方法を提供します。 あなたがそれを掛けてしまえば使い始めたのはかなり簡単です。 http://redux.js.org/docs/basics/UsageWithReact.htmlの設定を省略します。
そうのような減速を行います。
import * as config from './config';//I like to make a config file so it's easier to dispatch my actions etc
//const config.state = {param1: null}
//const config.SOME_FUNC = "test/SOME_FUNC";
export default function reducer(state = config.state, action = {}) {
switch(action.type) {
case config.SOME_FUNC:
return Object.assign({}, state, {
param1: action.param1,
});
break;
default:
return state;
}
}
}
は、お店のためにあなたの減速にそれを追加します。
すべてのコンポーネントをプロバイダにラップします。
ReactDOM.render(
<Provider store={store} key="provider">
<App>
</Provider>,
element
);
これで、プロバイダのすべての子コンポーネントでredux connectを使用できるようになりました。そのよう
:
import React, {Component} from 'react';
import {connect} from 'react-redux';
@connect(
state => (state),
dispatch => ({
someFunc: (param1) => dispatch({type: config.SOME_FUNC, param1: param1}),
})
)
export default class Child extends Component {
eventFunction = (event) => {
//if you wanted to update the store with a value from an input
this.props.someFunc(event.target.value);
}
render() {
return (
<h1>{this.props.test.param1}</h1>
);
}
}
あなたはReduxのhttps://github.com/redux-saga/redux-sagaこれをチェックアウトするために使用されます。これがあなたの最終目標です!サガは素晴らしいです!あなたがつかまえられたら、私に知らせてください!
はあなた 'someFunc'に' export'を削除し、あなた 'MYCOMPの内側に、この機能を入れてみました'クラス? – Jacky
もちろんジャッキーはうまくいくでしょう。しかし、いくつかのコンポーネントで 'someFunc()'を使用しています... – Stophface
あなたの状態を管理するためにHOCを使用し、ラップされたコンポーネントに小道具を渡すことができます。 https://facebook.github.io/react/docs/higher-order-components.html#use-hocs-for-cross-cutting-concerns –