【问题标题】:Why did setState not work in this case in NextJS?为什么 setState 在这种情况下在 NextJS 中不起作用?
【发布时间】:2021-03-02 16:10:09
【问题描述】:

大家好!
我有一个问题 - setState 在我的 NextJS + TS 应用程序中不起作用。
我通过 ReactHooks 尝试了我的状态,但没有任何效果,将组件更改为类,但没有任何效果。
我试图在没有 TS 的新创建的 CRA 应用程序上运行此组件。一切都在那里工作。

组件通过 props 接收数组并将其呈现为按钮。
State 包含两个属性,currentActive 和 selected。
当用户点击按钮时,第一个函数被触发,它应该更新 this.state.currentActive
然后是第二个应该更新 this.state.selected

在 this.setState 函数中,我调用了一个回调,它应该向控制台打印状态已更新。但是没有输出,看起来 this.setState 没有被调用!

import React, { Component } from 'react';

import { SelectFieldComp } from './styles';

interface IProps {
  title: string;
  name: string;
  options: {
    id: number;
    text: string;
    active: boolean;
  }[];
  multiple?: boolean;
  setFieldValue?: any;
}

interface IState {
  currentActive: number[];
  selected: string[];
}

class SelectField extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      currentActive: [],
      selected: []
    };
  }

  updateCurrentActive = id => {
    const { multiple } = this.props;
    const { currentActive } = this.state;
    const newCurrentActive: number[] = multiple
      ? Object.assign([], currentActive)
      : [];

    if (multiple && newCurrentActive.indexOf(id) > 0) {
      newCurrentActive.splice(newCurrentActive.indexOf(id), 1);
    } else {
      newCurrentActive.push(id);
    }

    this.setState(
      () => ({ currentActive: newCurrentActive }),
      () => {
        console.log('update state in updateCurrentActive: ', this.state);
      }
    );
  };

  updateSelected = () => {
    const { currentActive } = this.state;
    const { options } = this.props;
    const newArr: string[] = [];

    options.forEach(item => {
      if (currentActive.indexOf(item.id) > 0) {
        newArr.push(item.text);
      }
    });

    this.setState(
      () => ({ selected: newArr }),
      () => {
        console.log('update state in updateSelected: ', this.state);
      }
    );
  };

  render() {
    const { currentActive, selected } = this.state;
    const { title, name, options, setFieldValue } = this.props;

    return (
      <SelectFieldComp>
        <h3>{title}</h3>
        <div>
          {options.map(({ id, text }) => {
            const classList = currentActive.indexOf(id) > 0 ? 'active' : '';

            return (
              <button
                key={id}
                type="button"
                className={classList}
                onClick={() => {
                  this.updateCurrentActive(id);
                  this.updateSelected();
                  setFieldValue(name, selected);
                }}
              >
                {text}
              </button>
            );
          })}
        </div>
      </SelectFieldComp>
    );
  }
}

export default SelectField;

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

    this.setState() 的第一个参数是一个对象,看起来你在传递一个函数。

    试试

     this.setState({ currentActive: newCurrentActive });
    

    调用 setState 后立即进行控制台日志记录也将不起作用,因为 setState 的内部是异步的,因此它们可能尚未设置。

    您可以在this.props 之后的渲染方法中使用console.log,因为这将显示组件重新渲染时的状态。

    【讨论】:

    • 它也不起作用。数组 currentActive 和 selected 不适合。我在我的 render() {} 开头做 console.log (this.state) 并且总是有空数组
    猜你喜欢
    • 2018-08-28
    • 2017-11-26
    • 2010-12-29
    • 1970-01-01
    • 2021-08-05
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多