简体   繁体   English

反应钩子更改 state object 值

[英]react hooks change state object value

Let's say I have a state variable like:假设我有一个 state 变量,例如:

const [params,setParams] = useState({name:'bill' , surname:'mysurname'});

I want to create a function that gets a string as an input.我想创建一个获取字符串作为输入的 function。 If the string is a value of one of my object's keys then set the object key value to "".如果字符串是我的对象键之一的值,则将 object 键值设置为“”。

Example例子

  input = "bill" 
   if "bill" is a value of a key in my object then set the corresponding key's value to "" 
   I have input= " bill" and name:"bill" so set name:""

I want to do this using setParams of course.我当然想使用 setParams 来做到这一点。 I would appreciate your help.我会很感激你的帮助。

If you're changing all of the properties, you can use setParams in the simple way:如果要更改所有属性,则可以以简单的方式使用setParams

setParams({name: "New name", surname: "New surname"});

If you're only updating some of the properties, the usual way is using spread syntax with setParams , like this:如果您只更新某些属性,通常的方法是使用带有setParams的扩展语法,如下所示:

setParams(params => ({
    ...params,             // Reuse the previous properties
    name: "New name here", // Overwrite the new ones
}));

Note using the callback form, because you're reusing part of the state item, so you want to ensure you're not using stale state because another state update is pending.请注意使用回调表单,因为您正在重用 state 项目的一部分,因此您要确保您没有使用过时的 state,因为另一个 state 更新正在等待中。


In an edit you've said:在编辑中你说过:

input = "bill"输入=“账单”

if "bill" is a value of a key in my object then set the corresponding key's value to ""如果“bill”是我的 object 中某个键的值,则将相应键的值设置为“”

I have input= " bill" and name:"bill" so set name:""我有 input=" bill" 和 name:"bill" 所以设置 name:""

Matching any property seems unusual, but you just put a condition in the callback:匹配任何属性似乎不寻常,但您只需在回调中放置一个条件:

setParams(params => {
    for (const name in params) {
        if (params[name] === input) {
            // It's a match, clear it
            params = {
                ...params,
                [name]: "",
            };
            break;
        }
    }
    return params;
});

That replaces just the first match.这仅替换了第一场比赛。 To replace all matches:要替换所有匹配项:

setParams(params => {
    let newParams;
    for (const name in params) {
        if (params[name] === input) {
            // It's a match, copy the params if we haven't already
            newParams = newParams || {...params};
            // Clear the property
            newParams[name] = "";
        }
    }
    return newParams;
});

If input doesn't match anything, returning the same object from the callback won't result in a re-render, since React will see nothing changed.如果input不匹配任何内容,从回调中返回相同的 object 不会导致重新渲染,因为 React 不会看到任何变化。

The following function will search the values of the given obj .下面的 function 将搜索给定obj的值。 If it finds one matching exactly the given searchValue , it will return another object having that value set to the empty string.如果它找到一个与给定的searchValue完全匹配的,它将返回另一个object 并将该值设置为空字符串。 If many values match, it replaces only the first.如果许多值匹配,它只替换第一个。 If none matches, it returns the same object.如果没有匹配,则返回相同的 object。 The code assumes fairly modern Javascript features are available.该代码假定相当现代的 Javascript 功能可用。

function t(obj, searchValue) {
  const foundKey = Object.keys(obj).find(key => obj[key] === searchValue);
  if (foundKey) {
    return {
      ...obj,
      [foundKey]: ''
    };
  }
  return obj;
}

 const MyComponent = (props) => { const {} = props; const [params,setParams] = useState({name:'bill', surname:'mysurname'}); const myFunction = (input) => { if(input === params.name){ setParams({...params, name:""}); } } if(condition){ myFunction(someinput) } return <Text>name is {params.name}</Text>; }

You could write it like this:你可以这样写:

  const clearParam = (key) => {
    if (Object.keys(params).includes(key)) {
      setParams((states) => ({ ...states, [key]: '' }));
    }
  };

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

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