Javascript 当父组件中的状态已更新时自动渲染子组件

Javascript 当父组件中的状态已更新时自动渲染子组件,javascript,reactjs,components,Javascript,Reactjs,Components,父组件仪表板保存我添加到我的监视列表中的每个列表项的状态。不幸的是,每次我添加项目时,它都会被添加到数据库中,但只有在我刷新浏览器时才会显示 class UserDashboard extends React.Component { state = { data: [] } componentWillMount() { authService.checkAuthentication(this.props); } isLoggedIn = () =>

父组件
仪表板
保存我添加到我的
监视列表
中的每个
列表项
的状态。不幸的是,每次我添加项目时,它都会被添加到数据库中,但只有在我刷新浏览器时才会显示

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>
    );
  }
}
类UserDashboard扩展了React.Component{ 状态={ 数据:[] } 组件willmount(){ authService.checkAuthentication(this.props); } 伊斯洛格丁=()=>{ 返回authService.authenticated() } getAllCoins=()=>{ //从后端API获取 } addWishlist=()=>{ 这个。getAllCoins() .然后(事情=>{ 这是我的国家({ 数据:事物 }) }) log(“已单击子项”) } componentDidMount(){ 这个。getAllCoins() .然后(事情=>{ 这是我的国家({ 数据:事物 }) }) } render(){ 返回( 您好,欢迎来到用户仪表板 ); } } 用户观察列表:

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>
    )
  }
}
类UserWatchlist扩展了React.Component{ 建造师(道具){ 超级(道具) } //componentDidUpdate(prevProps){ //if(this.props.data!==prevProps.data){ //console.log(“当前”,this.props.data) //console.log(“PREVs”,prevProps.data) // } // } render(){ 返回( 以下是您正在观看的TSSSSY:
    { this.props.data.map((coin,idx)=>{ 返回 }) }
) } } 显示要监视的潜在项目的搜索栏:

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>
    );
  }
}
类搜索栏扩展React.Component{
建造师(道具){
超级(道具)
此.state={
硬币:[],
搜索值:“
}
}
searchHandler=e=>{
e、 预防默认值()
常量值=e.target.value
这是我的国家({
searchValue:value
});
如果(值==“”){
这是我的国家({
硬币:[]
})
}否则{
这个文件名为getInfo()
}
}
getInfo=()=>{
//搜索API
}
addWishlist=()=>{
this.props.addWishlist();
}
render(){
const{coins,searchValue}=this.state
返回(
    { coins.filter(searchingFor(searchValue)).map(coin=> ) }
); } }
以及单击要添加的实际货币:

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>
    )
  }
}
class.Component{
addToWatchlist=()=>{
//发布到后端数据库以保存
};
获取(“/api/添加硬币”,设置)
.catch(错误=>{
返回错误
})
}
clickHandler=()=>{
this.addToWatchlist()文件
this.props.addWishlist()
}
render(){
返回(
  • {this.props.coin.currency} +列入观察名单
  • ) } }
    正如你们所看到的,我一直在给孩子们送道具。当我单击按钮添加到监视列表时,我看到出现console.log消息,说“CHILD WAS CLICKED”。我甚至尝试过再次调用该方法从后端API获取数据

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


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

    您可能忘记等待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()
        })
      }
    

    您能为此提供codesandbox吗?
    getAllCoin()
    是否实际返回了承诺?我看到您在该方法上调用了
    .then()
    ,可能您的getAllCoin方法没有返回承诺,这可能就是您的setState没有被调用的原因。尝试将console日志作为setState的第二个参数,如果调用了console.log,请告诉我。@mxdi9i7是的,它返回API调用(在一个单独的帮助文件中),并且我确实将结果视为componentDidMount()的一部分。似乎当我尝试从addWishlist()中重新运行函数时,它没有发生。再说一次,也许我不应该做两个这样的调用(这是一个糟糕的设计吗?)您是否尝试将控制台日志记录为setState的回调
    this.setState({data:thing},console.log('ping'))
    @mxdi9i7抱歉,当时正在工作。但是,我刚刚尝试了这个:
    addWishlist=()=>{this.getAllCoins()。然后(things=>{this.setState({data:things}}),console.log(“PING”)}
    我在控制台中看到了“add”操作之后的PING,但是我仍然需要刷新浏览器尝试一下,我得到
    类型错误:无法读取未定义的属性“then”
    。addToWatchlist正在完成;我可以看到console.log语句在事件期间发生