【发布时间】: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