我正在尝试将一个类组件转换为功能组件,我可以按照一些步骤来执行此操作,但我不确定如何更改其余代码以使其工作。我不清楚的部分是删除setState
。我也会在这个问题的末尾添加我到目前为止所做的事情。
类组件:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
newTodoName: '',
todos: todos
};
}
generateNewId() {
return this.state.todos.length + 1;
}
onSubmit(event) {
event.preventDefault();
var newTodos = this.state.todos.slice();
newTodos.push({
id: this.generateNewId(),
name: this.state.newTodoName,
complete: false
});
this.setState({todos: newTodos, newTodoName: ''});
}
onClick(id) {
var todoItems = this.state.todos.slice();
for (let i = 0; i < this.state.todos.length; i++) {
if (todoItems[i].id === id) {
var newComplete = !todoItems[i].complete;
todoItems[i].complete = newComplete;
}
}
this.setState({
todos: todoItems
});
}
onChange(event) {
this.setState({newTodoName: event.target.value});
}
到目前为止我做了什么:
function App(props) {
const [newTodoName,setName] = useState("");
const [todos,setArray] = useState(todos);
const generateNewId() = () => {
return setArray(todos.length + 1)
}
const onSubmit() = (event) => {
event.preventDefault();
var newTodos = todos.slice();
var id =
newTodos.push({
id: generateNewId(),
name: newTodoName,
complete: false
});
this.setState({todos: newTodos, newTodoName: ''});
}
const onClick() = (id) => {
var todoItems = todos.slice();
for (let i = 0; i < todos.length; i++) {
if (todoItems[i].id === id) {
var newComplete = !todoItems[i].complete;
todoItems[i].complete = newComplete;
}
}
this.setState({
todos: todoItems
});
}
const onChange() = (event) =>{
this.setState({newTodoName: event.target.value});
}
如何将此类组件转换为功能组件?