React:来自不同子组件的子组件中的触发方法

Sve*_*ven 5 reactjs

我在 React 中创建了两个组件,<Search />它们<List />都是<App />.

\n\n

当单击 中的按钮时<Search />,我想从 API 中获取某些内容并在 中显示结果<List />。虽然我通过在内部执行 fetch<App />并将响应作为 prop 传递给 来完成此工作<List />,但我更愿意将 fetch 封装在内部<List />

\n\n

不幸的是,我很难找到一种方法来做到这一点。“React 方式”可能是通过一些巧妙的 prop 传递来做到这一点,但我还没有找到一种巧妙的方法来做到这一点 \xe2\x80\x93 即使需要一个“shouldFetch”布尔值获取后重置似乎很麻烦并且会触发不必要的渲染。

\n\n

这个答案用于refs类似的可能有效的东西,但实际上我有点犹豫是否要尝试它,因为refs根据 React 文档,它似乎有点肮脏,因为它们“必须修改典型数据流之外的子级”。

\n\n

单击<List />按钮后如何指示我的组件执行某些操作?<Search />

\n\n

如果需要,我可以提供代码 \xe2\x80\x93 但希望这个问题比我看起来更简单。

\n

小智 3

一个自然的选择是在 中 创建一个状态布尔变量<App />,按下按钮时触发<Search />,然后<List />在布尔状态从false变为时使用一些逻辑来获取数据true

例如:

class App extends React.Component {
  constructor() {
    super();
    this.state = { fetchData: false }
  }

  render() {
    return (
      <div>
        <Search onClick={() => this.setState({fetchData: true})} />
        <List shouldFetch={this.state.fetchData} onFetch={() => this.setState({fetchData: false})} />
      </div>
    )
  } 
}
Run Code Online (Sandbox Code Playgroud)

然后在你的<List />组件中:

class List extends React.Component {
  componentWillReceiveProps(nextProps) {
    if ( !this.props.shouldFetch && nextProps.shouldFetch ) {
      // Fetch data here and set it in state, for example
      // After fetch, don't forget to call onFetch() to reset the boolean
    }
  }

  ... // more code
}
Run Code Online (Sandbox Code Playgroud)

<App />虽然这样可以,但是作为数据源使用也不错。这样你就可以抽象出只处理 UI 而没有网络逻辑的纯组件。这通常是一个很好的模型,可以帮助您将来重用组件。