首页 > 解决方案 > 我无法从我的子(类)组件更新我的父组件中的状态

问题描述


class App extends Component {
  state = {
    recipes: []
  };

  componentDidMount() {
    recipesData()
      .then(data => this.setState({ recipes: data.recipes }))
  }

  render() {
    return (
      <div className="App">
        <Search/>
        <RecipeList data={this.state.recipes} />
      </div>

class Search extends Component {
  state = {
    search: ""
  };

  handleChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const key = "KEY";
    const url = `https://www.food2fork.com/api/search?key=${key}&q=${
      this.state.search
    }&page=2`;
    fetch(url)
      .then(res => res.json())
      .then(res => {console.log(res)})
  };

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            name="search"
            value={this.state.search}
            onChange={this.handleChange}
          />
          <button type="submit">Search</button>
        </form>
      </div>

提前致谢。

标签: javascriptreactjsparent-child

解决方案


里面的数据RecipeList是从组件传递过来的App。并且当Search组件发生变化时,RecipeList也会发生变化。

因此,当Search组件发生变化时,我们必须告知App数据发生了变化。

所以常用的方法就是写 handleSubmit进去App传给Search

这是一个有效的代码框: https ://codesandbox.io/s/quirky-architecture-ktj3q ?fontsize=14

(我嘲笑了 fetch 部分)


更新:如果您有兴趣,我添加了一个功能组件版本。

https://codesandbox.io/s/shy-worker-8s3zi?fontsize=14

有关功能组件和 Hook 的更多信息:https ://reactjs.org/docs/hooks-intro.html


推荐阅读