简体   繁体   English

为什么下面的 react 功能组件不能正常工作?

[英]Why the following react functional component does not work properly?

It is quite straight forward, when you press "add" it should add(and it adds) and when you press "remove" it should pop the last element and re-render the list but it doesn't.这很简单,当您按“添加”时,它应该添加(并且它会添加),当您按“删除”时,它应该弹出最后一个元素并重新渲染列表,但事实并非如此。 I am make mistake somewhere?我在某个地方犯了错误?

import React, { useState, useEffect } from 'react';


const Test = () => {
    const [list, setList] = useState([]);
    const add = () => {
        setList([list.length, ...list]);
    }

    const remove = () => {
        list.pop();
        setList(list);
    }

    useEffect(() => {
        console.log(list)
    }, [list])

    return (<ul>
        <button onClick={add}>add</button>
        <button onClick={remove}>remove</button>
        {list.map(el => <li>{el}</li>)}
    </ul>)
}

export default Test;

UPDATE: Actually it updates the state by removing the last element but the re-render happen only when button "add" is pressed更新:实际上它通过删除最后一个元素来更新 state 但重新渲染仅在按下按钮“添加”时发生

It's not recommended to modify the state itself because it is immutable.不建议修改 state 本身,因为它是不可变的。

So instead using .pop() on the original state of the array, first I suggest to clone that one and remove the required element from there, then the result should passed to setList() function.因此,而不是在数组的原始 state 上使用.pop() ,首先我建议克隆那个并从那里删除所需的元素,然后将结果传递给setList() function。

Try as the following instead:请尝试以下操作:

const remove = () => {
    const copy = [...list];
    copy.pop();
    setList(copy);
}

Think about the following:考虑以下几点:

 const list = [1,3,5,6,7]; const copy = [...list]; copy.pop(); console.log(list); console.log(copy);

I hope this helps!我希望这有帮助!

You need to set a new array in this case, setList(list) will not cause React to re-render because it's still the same array you're using.在这种情况下,您需要设置一个新数组, setList(list)不会导致 React 重新渲染,因为它仍然是您正在使用的同一个数组。

Try setList([...list]) in your remove function.remove function 中尝试setList([...list])

There's also an alternative to pop , and doesn't mutate the original variable: pop还有一个替代方法,并且不会改变原始变量:

  const remove = () => {
    const [removed, ...newList] = list
    setList(newList)
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM