简体   繁体   中英

How to change the state of a component when another changes?

How can I change the state of a component when another changes?

When the state of a select changes AssetType , the value of the select AssetTypeCategory must be set to 0

  const handleAssetType = (e)=>{
    setAssetType(e.target.value),
    setAssetTypeCategory(0),
  }


  <div>
    <label htmlFor="AssetType>Asset Type:</label>
    {Array.isArray(state.AssetType) ? (
      <select
        name="AssetType"
        id="AssetType"
        value={state}
        onChange={handleAssetType }
      >
        <option key="0" value="0">
          -- PICK A ITEM--
        </option>
        {state.AssetType.map((x) => (
          <option key={x.id} value={x.id}>
            {x.name}
          </option>
        ))}
      </select>
    ) : null}
  </div>

Do you using class or functional component? It looks like you using class component, u cant change class component's state this way, use setState and spread "..." operator.

The code is wrong for two reasons.

1 - You dont need to use comma to separate functions. The code would be:

  const handleAssetType = (e)=>{
  
    setAssetType(e.target.value)
    setAssetTypeCategory(0)
  }

2 - If you do setAssetType(e.target.value) the value is a int, so AssetType is not an array, making a blank page.

You should exec your handleAssetType function in this way.

const handleAssetType = (e)=>{
    setAssetType(e.target.value),
    setAssetTypeCategory(0),
  }

  <div>
    <label htmlFor="AssetType>Asset Type:</label>
    {Array.isArray(state.AssetType) ? (
      <select
        name="AssetType"
        id="AssetType"
        value={state}
        onChange={(e) => handleAssetType(e) }
      >
        <option key="0" value="0">
          -- PICK A ITEM--
        </option>
        {state.AssetType.map((x) => (
          <option key={x.id} value={x.id}>
                {x.name}
              </option>
            ))}
         </select>
      ) : null}
  </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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