私はReactアプリケーションを構築しており、タブをクリックすると、タブをクリックすると特定のコンポーネントがレンダリングされます。状態更新を条件付きでレンダリングされたReactコンポーネントに直接プッシュしますか?
まず、私の親コンポーネント:
class Interface extends Component {
constructor(props) {
super(props);
this.chooseTab = this.chooseTab.bind(this);
this.state = {
current: 'inventory',
inventory: [],
skills: [],
friends: [],
notifications: {}
};
}
chooseTab(tabID) {
this.setState({ current: tabID });
chooseComponent(tabID) {
if (tabID === 'skills') return Skills;
else if (tabID === 'inventory') return Inventory;
else if (tabID === 'friends') return FriendsList;
}
render() {
const tabID = this.state.current;
const CustomComponent = this.chooseComponent(tabID);
return (
<div className='column' id='interface'>
<div className='row' id='tabs'>
<ActiveTab
current={this.state.current}
tabID='skills'
chooseTab={this.chooseTab}
/>
<ActiveTab
current={this.state.current}
tabID='inventory'
chooseTab={this.chooseTab}
/>
<ActiveTab
current={this.state.current}
tabID='friends'
chooseTab={this.chooseTab}
/>
</div>
<TabBody>
<CustomComponent
data={this.state[tabID]}
notifications={this.state.notifications}
/>
</TabBody>
</div>
);
}
}
3 ActiveTabさんと1 TabBodyをレンダリング:
const ActiveTab = (props) => {
const isActive = props.tabID === props.current ? 'active' : 'inactive';
return (
<button
className={`active-tab ${isActive}`}
onClick={() => props.chooseTab(props.tabID)}
>{props.tabID}
</button>
);
};
const TabBody = (props) => {
return (
<div className='tab-body'>
{props.children}
</div>
);
};
これは正常に動作し、それは明らかintended wayですこの問題を処理するしかし、状態オブジェクトをFriendsList
コンポーネントに移動することができます(これは友人にとって一意であるため)FriendsList
が現在TabBodyによってレンダリングされているコンポーネントではない場合でも、別のコンポーネントからsetState
を別のコンポーネントからトリガーすることができます。 、マウントされていない)。
私は現在、具体的な行動とsetState
がターゲット要素のComponentWillMount()
ライフサイクルメソッドで定義され、それがリモート状態変化を活性化されているもののコンポーネントから実行されますグローバルに使用できるactions
クロージャを使用してリモート状態の変化をトリガしています。私は簡潔さのためにInterface
のうちのそれらを残しました。
これはどのように処理しますか? notifications
をInterface
に残し、そこにアクションを定義し、Reactが通過する小道具を下ろすようにする唯一の選択肢はありますか?または、タブのコンポーネントと条件付きレンダリングを作成して、別のコンポーネントからタブの非表示コンポーネントに状態変更をトリガーすることができます。notifications
と対応するアクションをFriendsList
に移動しますか?
あなたは[redux](http://redux.js.org/)の使用を検討しましたか? – Matthew
私は持っているし、それは確かに私の現在のものよりもエレガントな解決策ですが、残念ながらチームの残りの部分は今のところ確信がありません。その間に別の解決策を探しています。 –
その場合:インタフェースに通知を残し、そこにアクションを定義し、リアクションが渡している小道具を処理させるようにする唯一のオプションはありますか?はい、あなたの唯一の選択肢です。あなたはredux/mobx /その他の状態管理ライブラリを使うことができます。そうしないと、状態を更新するための関数だけでなく、コンポーネント階層内の状態を高く保ち、小道具を渡す必要があります。 – Matthew