【问题标题】:ReactJS - passing part of onClick function as a prop from parent componentReactJS - 将部分 onClick 函数作为来自父组件的道具传递
【发布时间】:2020-08-09 03:58:09
【问题描述】:

大家好,我正在尝试将 prop 中的命令从父组件传递给子组件。问题是,单击我的按钮后,必须更改父组件中的状态才能打开预期的侧边栏。我似乎没有正确使用 onClick 函数末尾的 .then() 部分,因为我收到错误:× 未处理的拒绝(TypeError):无法读取未定义的属性“then”

儿童组件:

return (
          <div
            className="results-item"
            onClick={async () => {
              let place_detail;
              try {
                const URL = `https://maps.googleapis.com/maps/api/place/details/json?place_id=${places.place_id}&fields=name,rating,formatted_phone_number&key=
      MYAPIKEY`;
                const response = await axios.get(URL);
                console.log(response.data);
                place_detail = response.data.results;
              } catch (error) {
                console.log(error.message);
              }

              this.setState({ place_detail }).then(this.props.sideBarOpen);
            }}
          >
            <ResultsItem
              name={places.name}
              image={Thumbnail}
              rating={places.rating}
              rating_total={places.user_ratings_total}
            />
          </div>
        );

父组件:

<Search sideBarOpen={() => setOpen(!open)} />

【问题讨论】:

标签: reactjs


【解决方案1】:

setState 不返回承诺。改用回调:

this.setState({ place_detail }, () => {
   this.props.sideBarOpen();
});

【讨论】:

    【解决方案2】:

    您不能在setState 通话中使用.then。您可以使用 setState 的回调函数来执行您要执行的操作 -

    this.setState({ place_detail }, () => this.props.sideBarOpen());
    

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 2020-11-19
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2019-07-03
      • 2019-12-31
      相关资源
      最近更新 更多