首页 > 解决方案 > 将 Class 组件转换为功能组件 React

问题描述

我正在尝试将一个类组件转换为功能组件,我可以按照一些步骤来执行此操作,但我不确定如何更改其余代码以使其工作。我不清楚的部分是删除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});
}

如何将此类组件转换为功能组件?

标签: reactjs

解决方案


你的状态应该这样声明

const [newTodoName, setNewTodoName] = useState("");
const [todos, setTodos] = useState(todoProps);

如果你想改变一个状态,你不应该使用this.setState(...),但是

setNewTodoName("your string")
setTodos(YourTodos)

编辑:这是您的代码转换。

https://codesandbox.io/s/crazy-sid-09myu?file=/src/App.js:0-2376


推荐阅读