首页 > 解决方案 > 当父组件中的状态已更新时自动渲染子组件

问题描述

父组件Dashboard保存ListItem我添加到我的每个Watchlist. 不幸的是,每次我添加一个项目时,它都会被添加到数据库中,但只有在我刷新浏览器时才会显示。

class UserDashboard extends React.Component {
  state = {
    data: []
  }

  componentWillMount() {
    authService.checkAuthentication(this.props);
  }

  isLoggedIn = () => {
    return authService.authenticated()
  }

  getAllCoins = () => {
    //fetches from backend API
  }

  addWishlist = () => {
    this.getAllCoins()
      .then(things => {
        this.setState({
          data: things
        })
      })
    console.log("CHILD WAS CLICKED")
  }

  componentDidMount() {
    this.getAllCoins()
      .then(things => {
        this.setState({
          data: things
        })
      })
  }

  render() {
    return (
      <div className="dashboard">
        <h1>HI, WELCOME TO USER DASHBOARD</h1>
        <SearchBar
          addWishlist={this.addWishlist}
        />
        <UserWatchlist
          data={this.state.data}
        />
      </div>
    );
  }
}

用户关注列表:

class UserWatchlist extends React.Component {
  constructor(props) {
    super(props)
  }

  // componentDidUpdate(prevProps) {
  //   if (this.props.data !== prevProps.data) {
  //     console.log("CURRENT", this.props.data)
  //     console.log("PREVs", prevProps.data)
  //   }
  // }

  render() {
    return (
      <div>
        <h2>These are tssssyou are watching:</h2>
        <ul className="coin-watchlist">
          {
            this.props.data.map((coin, idx) => {
              return <ListItem key={idx}
                              coin={coin.ticker}
                              price={coin.price}
                      />
            })
          }
        </ul>
      </div>
    )
  }
}

显示潜在项目的搜索栏:

class SearchBar extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      coins: [],
      searchValue: ""
    }
  }


  searchHandler = e => {
    e.preventDefault()
    const value = e.target.value

    this.setState({
      searchValue: value
    });

    if (value === "") {
      this.setState({
        coins: []
      })
    } else {
      this.getInfo()
    }
  }

  getInfo = () => {
    // Searches the API
  }

  addWishlist = () => {
    this.props.addWishlist();
  }

  render() {
    const {coins, searchValue} = this.state

    return (
      <div className="coin-search">
        <form>
          <input
            type="text"
            className="prompt"
            placeholder="Search by ticker symbol"
            value={searchValue}
            onChange={this.searchHandler}
          />
        </form>
        <ul className="search-suggestions">
          {
            coins.filter(searchingFor(searchValue)).map( coin =>
              <Currency
                coin={coin}
                addWishlist={this.addWishlist}
              />
            )
          }
        </ul>
      </div>
    );
  }
}

以及被点击添加的实际货币:

class Currency extends React.Component {

  addToWatchlist = () => {
    // POST to backend DB to save
    };

    fetch("/api/add-coin", settings)
      .catch(err => {
        return err
      })
  }

  clickHandler = () => {
    this.addToWatchlist()
    this.props.addWishlist()
  }

  render() {
    return(
      <div className="search-results">
          <li>
            <h3> { this.props.coin.currency } </h3>
            <button
              className="add-to-list"
              onClick={this.clickHandler}
              >
                + to Watchlist
              </button>
          </li>
      </div>
    )
  }
}

正如你所看到的,我一直向下发送道具给孩子。当我单击添加到监视列表的按钮时,我看到出现了 console.log 消息,上面写着“儿童被点击”。我什至尝试过再次调用从后端 API 获取的方法。

此外,在 UserWatchlist 中,我尝试了 componentDidUpdate,但 prevProps 和 this.props 都显示了完全相同的数据数组。在链条的某个地方,我的数据正在丢失。

这也是我第一次在这里发布问题,所以如果可以改进,我很乐意添加额外的细节并为这个社区做出贡献

标签: javascriptreactjscomponents

解决方案


您可能忘记等待 addToWatchlist 完成:

  addToWatchlist = () => {
    // POST to backend DB to save
    return fetch("/api/add-coin", settings)
      .catch(err => {
        return err
      })
  }

  clickHandler = () => {
    this.addToWatchlist().then(() => {
      this.props.addWishlist()
    })
  }

推荐阅读