簡體   English   中英

從愚蠢的孩子反應Redux更新狀態

[英]React Redux update state from dumb child

有沒有辦法從啞子組件更新父狀態? 我有網格布局,有兒童(標題和正文),我想使用標題作為輸入過濾器。 我將我的網格連接到帶有父組件的數據庫,將我的所有數據傳遞給正文和標題,但我希望從標題到連接的智能組件獲取過濾器。 我發現的唯一方法是連接GridHeader來存儲數據並直接傳遞給它。

我的solutoin的問題是我想在不同的頁面中使用不同數據類型的網格,所以我需要所有的網格組件都是愚蠢的。 使用我的解決方案,我必須為每個數據/表類型編寫特定的GridHeader,並將每個標頭連接到不同的商店密鑰。 一個將連接到catalog: store.catalog第二個將是users: store.users等...我的解決方案它不DRY我不喜歡它:/請幫助

這是我的GridHeader:

import React from 'react';

import { connect } from 'react-redux';
import { filterCatalog, setFilters } from '../../redux/actions/catalogActions';

@connect((store) => {
    return {
        catalog: store.catalog
    };
})
export default class GridHeader extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(e) {
        const name = e.target.name;
        let filters = {
            [name]: e.target.value
        }
        this.props.dispatch(setFilters(filters))
    }

    handleSubmit(e) {
        if (e.which == 13){
            e.target.blur();
            //console.log('submit', this.props.catalog.filters)
            this.props.dispatch(filterCatalog(this.props.catalog.filters))
        }
    }

    render() {
        const headerItem = this.props.headers.map((x) => {
            return (
                <th class={x.class} key={x.name}>
                <div class="input-field">
                    <input type={x.type} id={x.id} name={x.name} placeholder={x.placeholder} class={x.class} disabled={x.disabled} onChange={this.handleChange} onKeyPress={this.handleSubmit}/>
                    <label for={x.name}>{x.label}</label>
                </div>
                <a class="filter-button hidden">
                    <i class="material-icons">backspace</i>
                </a>
            </th>
            )
        });

        return (
            <thead>
                <tr>
                    {headerItem}
                </tr>
            </thead>
        );
    }
}

您可以創建將為GridHeader提供數據的包裝器組件。 例如:

首次使用

@connect((store) => {
  return {
      catalog: store.catalog
  };
})
export default class FirstWrapperGridHeader extends React.Component {
  render() {
    <GridHeader {...props} />
  }
}

第二種用法:

@connect((store) => {
  return {
      catalog: store.anotherData
  };
})
export default class SecondWrapperGridHeader extends React.Component {
  render() {
    <GridHeader {...props} />
  }
}

你的GridHeader應該沒有連接到redux商店,應該是愚蠢的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM