【问题标题】:Sharing React Component props with grandchildren components与孙组件共享 React 组件道具
【发布时间】:2019-12-20 18:22:30
【问题描述】:

我正在努力弄清楚如何与 react/typescript 中组件的孙子共享道具。为什么构造函数道具被覆盖?


class Resource extends Component<IResourceProps, IResourceState> {

  state:IResourceState = {

  }

  _finder: new this.props.finder({api: this.props.api})

  render() {

    return (
      <div>
        <Switch>
            <Route path={this.props.path} component={() => {return this._finder}} />
        </Switch>
      </div>
    )
  }

}

export default Resource;
class UserFinder extends React.Component<IResourceFinderProps, IResourceFinderState> implements IResourceFinder {

    _data:  any[] = []

    load = (response: QueryResponse): void => {
        this._data = response.records;
    }

    constructor(props:IResourceFinderProps) {
        super(props);
    }

    componentDidMount() {
        this.props.api.query({  //<-------- this.props.api is undefined! Why?
            page: 0,
            pageSize: 100
          }, (response:QueryResponse) => {
              this.load(response);
        })
    }

    render() {
        const columns = [
            {
                title: 'Name',
                dataIndex: 'firstName',
                key: 'firstName'
            }
        ];
        return (
            <div>
                <Table columns={columns} rowKey="userId" dataSource={this._data} />
            </div>
        )
    }
}

export default UserFinder

App.js

<Route  path="/users" finder={UserFinder} api={this.api} />

本质上,我想与 Route 的所有子节点共享 api 属性,而不必分别在每个子节点上显式设置它。也许,另一种解决方案可能是以某种方式让孩子参考祖父母。我有哪些选择?

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    首先,如果您只想通过路由器传递道具,请使用道具render 而不是component。例如:

    <Route path={this.props.path} render={(props) => <Component {...props} additionalProps={...} />} />
    

    如果您真的想在不传递 props 的情况下共享状态,您将需要像全局状态这样的东西。在那里,您有不同的选择。

    • 以前最常用的是redux(参见docs 和众所周知的tutorial)。
    • 随着 React 更新和钩子的支持,有更简单的方法来构建这样一个全局状态系统。您可以使用 useContextuseReducer 从头开始​​构建它,例如 this
    • 或者您可以只使用ReactN,它为您提供开箱即用的全局状态(请参阅here

    【讨论】:

    • 我还打算建议全局状态/商店。除了 Mika 所说的,MobX 非常好用。
    猜你喜欢
    • 2019-05-31
    • 2020-09-22
    • 2021-06-18
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2018-10-13
    • 2021-02-23
    • 2019-02-12
    相关资源
    最近更新 更多