更新处于使用状态的对象并立即查看更改的最佳方法是什么

What is the best way to update an object in a usestate and see the change immediately

const TestScreen = (props) => {

    const [data, setData] = useState([ 
            { "id": "0", "user": "Lisa","amount": 1 },
        ]);

        return(
            <View style={{
                            flex:1, 
                            alignItems:'center',
                            justifyContent:'center'
                        }}>
            <Text>amount : {data[0].amount}</Text>
            <Text>User : {data[0].user}</Text>
            <Button title="update" onPress={()=>setData(??????)}></Button>
          </View>
           
        )
    }
  
  export default TestScreen;

在用户 Lisa 上添加金额的最佳方法是什么?我可以 // setData([{ "id": "0", "user": "Lisa","amount": data[0].amount + 1}]) 但是我有 5 个用户还是 20 个?

即使有返回函数也没有任何更新,除了控制台记录 告诉我实际值

   let countAddFunc =(getArr)=>{
          let arr = getArr
          arr[0].amount++
          console.log(arr[0].amount);
          return(
            arr
          )
        }

<Button title="update" onPress={()=>setData(countAddFunc(data))}></Button>

你能试试这样吗,将第二个参数作为你要更新的用户 ID 传递

<Button title="update" onPress={()=>setData(countAddFunc(data, 0))}></Button>

let countAddFunc =(getArr, id)=>{
          const arrCopy = [...getArr]
          const user = arrCopy.find(u => u.id === id )
          if (user) {
             user.amount++
          }
          return arrCopy
        }

实际上你是直接修改状态,我们不能直接更新状态,getArr只是对状态中数据的引用,所以,我们创建了一个数组的副本,修改了复制的数组,然后我们设置这个新数组进入状态,关于抛出未定义错误的代码,添加一个检查,if (user) user.amount++ 并确保你发送的 id onPress={()=>setData(countAddFunc(data, 0) )}实际存在

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately. setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

阅读官方文档了解更多信息here

此外,如果您希望回调立即触发并进行更改,您也可以将 useRef 或 useEffect 与依赖项数组一起使用。

React 中的一个关键概念是 Do Not Modify State Directly。有时这可能很棘手,尤其是在处理嵌套数据时,例如您的示例(number 作为数组内对象的 属性)。

下面,我重构了您的代码并添加了注释以帮助解释。通过创建一个更新状态的函数,并将该函数传递给每个子组件的道具,子组件将能够通过调用该函数来更新状态。

const {useState} = React;

// component dedicated to displaying each item in the array
const Item = (props) => (
  <div style={{
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  }}>
    <div>Amount: {props.item.amount}</div>
    <div>User: {props.item.user}</div>
    <button onClick={() => {
      props.updateAmount(props.item.user);
    }}>Increment</button>
  </div>
);

const ItemList = () => {
  const [data, setData] = useState([
    {
      id: '0',
      user: 'Lisa',
      amount: 1,
    },
    {
      id: '1',
      user: 'Walter',
      amount: 3,
    },
  ]);

  const updateAmount = (user, changeAmount = 1) => {
    // find the index of the item we want
    const index = data.findIndex(item => item.user === user);

    // return early (do nothing) if it doesn't exist
    if (index === -1) return;

    const item = data[index];

    // don't modify state directly (item is still the same object in the state array)
    const updatedItem = {
      ...item,
      amount: item.amount + changeAmount,
    };

    // again, don't modify state directly: create new array
    const updatedArray = [...data];

    // insert updated item at the appropriate index
    updatedArray[index] = updatedItem;

    setData(updatedArray);
  };

  return (
    <ul>
      {data.map(item => (
        <li key={item.id}>
          <Item item={item} updateAmount={updateAmount} />
        </li>
      ))}
    </ul>
  );
};

ReactDOM.render(<ItemList />, document.getElementById('root'));
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>

<div id="root"></div>