在父组件中更新状态时自动呈现子组件

问题描述 投票:0回答:1

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

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消息,显示“CHILD WAS CLICKED”。我甚至尝试过再次调用方法从后端API获取。

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

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

javascript reactjs components
1个回答
0
投票

您可能忘记等待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()
    })
  }
© www.soinside.com 2019 - 2024. All rights reserved.