【问题标题】:State updates but component does not change状态更新但组件不变
【发布时间】:2021-08-19 23:48:56
【问题描述】:

我的任务是在给定网站上添加实现

有一个异步获取数据(票证)的功能,我需要允许一个排序选项。 排序发生在服务器端,通过按钮单击(排序类型),应获取排序后的数据并再次显示给用户。

我的想法是这样的:

  1. 点击按钮获取排序数据
  2. 使用 setState() 设置新的排序类型
  3. 这将调用 componentDidUpdate() 并将 setState() 异步设置为新数据。
  4. 最后的 setState() 应该调用 render 再次显示数据

除第 4 部分外,一切正常 - 正在调用渲染函数,但屏幕上的数据未更新。 我正在学习的课程是这样的:

App.tsx

export type AppState = {
  tickets?: Ticket[];
  search: string;
  sortBy: string;
};

export class App extends React.PureComponent<{}, AppState> {
    
  state: AppState = {
    search: "",
    sortBy: "none",
  };

  async componentDidMount() {
    this.setState({
      tickets: await api.getTickets(this.state.sortBy),
    });    
  }

  renderTickets = (tickets: Ticket[]) => {
    /*
     * more stuff here
     */
    // log that verifies I am getting the sorted data
    console.log("Tickets in rednerTickets: ")
    {tickets.map((t)=>{
        console.log(t);
    })}

    return (
      <ul className="tickets" id="all_tickets">
        {tickets.map((ticket) => (
          <CustomTicket t={ticket}></CustomTicket>
        ))}
      </ul>
    );
  };
  
  async componentDidUpdate(prevProp: AppState, prevState: AppState) {
    // if the sortBy state is different
    if (prevState.sortBy !== this.state.sortBy) {
      // perform getTickets and set the new tickets
      this.setState({
        tickets: await api.getTickets(this.state.sortBy),
      });
    }
  }

  render() {
    const { tickets } = this.state;
    console.log("tickets in render: ", tickets);
    return (
      <main>
        <h1>Tickets List</h1>
        
        <button
          onClick={() => {
            this.setState({ sortBy: "date" });
          }}>Sort By Date
        </button>

        <button
          onClick={() => {
            this.setState({ sortBy: "title" });
          }}>Sort By Title
        </button>

        <button
          onClick={() => {
            this.setState({ sortBy: "email" });
          }}>Sort By Email
        </button>

        {/* Calls the function that renders the tickets */}
        {tickets ? this.renderTickets(tickets) : <h2>Loading..</h2>}
      </main>
    );
  }
}
export default App;

CustomTicket 是另一个获取票证数据并显示它的类组件。

注意:

我尝试将 componentDidUpdate 更改为:

async componentDidUpdate(prevProp: AppState, prevState: AppState) {
    // if the sortBy state is different
    if (prevState.sortBy !== this.state.sortBy) {
        // perform getTickets and set the new tickets
      this.setState({
        tickets: await api.getTickets(this.state.sortBy),
      });
      // new line:
      ReactDOM.render(this.render(),document.getElementById('root'));
    }
  }

但它只适用于第一次点击,并且还带有“无法对未安装的组件执行反应状态更新”警告

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    试试这个:

    async componentDidUpdate(prevProp: AppState, prevState: AppState) {
      if (prevState.sortBy !== this.state.sortBy) {
        const tickets = await api.getTickets(this.state.sortBy)
        this.setState({
          tickets
        });
      }
    }
    

    在您的实现中,setState 正在调用并尝试获取票证,但票证是 Promise - 不需要数据。 首先需要先取票,然后拨打setState

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2016-10-02
      • 2021-06-08
      相关资源
      最近更新 更多