【问题标题】:Control subarray of state in form React以 React 形式控制状态子数组
【发布时间】:2019-10-22 13:41:48
【问题描述】:

我有一个带有盒子(div)的容器,在这些盒子里面有 N 个复选框。盒子和支票是从服务器获取的并在屏幕上列出。我需要控制复选框状态以根据其他获取设置检查。我该怎么做?

编辑: 我做了一个抓取来拿到盒子(模块)。每个模块都有一组复选框(我称之为功能):

modules = [{ id, name, features: [{ id, value }] } ]

我创建了一个新状态“checkModules”来控制复选框中的“已检查”属性。当我执行 fetchModules 时,我会根据获取的数据设置 checkModules。

const PermissionsPage = () => {

 const [modules, setModules] = useState([]);
 const [checkModules, setCheckModules] = useState([]); //state to control the checkboxes 'checked' propertie

 useEffect(() => {
  api.get('/modules').then(res => {
    setModules(res.data.modules);
    setCheckModules(
     res.data.modules.map(m => ({
       id: m.id,
       features: m.features.map(f => ({ id: f.id, checked: false }))
       }))
     );
  }
 });

 const handleChange = (m,f,e) => {
  let temp = checkModules;
  //the propertie is changed, but the checkbox don't 'check'.
  temp[m].features[f].checked = !temp[m].features[f].checked;
  setCheckModules(temp);
 }

return (){
  <div>
    {modules.map((module, m) => (
      <div>
      <span>{module.name}</span>
      {module.features.map((feature, f) => (<checkbox onChange={() => handleChange(m,f)} checked={checkModules[m] !== undefined ? checkModules[m].features[f].checked : false}/>))}
      </div>
    )}
  </div>
}
}

我试图重现代码以简化组件的使用 =)。

【问题讨论】:

  • 您需要向我们展示一些与您的问题相关的代码。
  • 我已经用一些代码更新了问题。

标签: reactjs forms axios


【解决方案1】:

我解决了。我将发布更改 =)。

const PermissionsPage = () => {

 const [modules, setModules] = useState([]);
 const [checkModules, setCheckModules] = useState([]); //state to control the checkboxes 'checked' propertie

 useEffect(() => {
  api.get('/modules').then(res => {
    setModules(res.data.modules);
    setCheckModules(
     res.data.modules.map(m => ({
       id: m.id,
       name: m.name,
       features: m.features.map(f => ({ id: f.id, name: f.name, checked: false }))
       }))
     );
  }
 });

 const handleChange = (m,f,e) => {
  let temp = [...checkModules]; //that's the point. You need to take the state as a new array;
  temp[m].features[f].checked = !temp[m].features[f].checked;
  setCheckModules(temp);
 }

return (){
  <div>
    {checkModules.map((module, m) => (
      <div>
      <span>{module.name}</span>
      {checkModules[m].features.map((feature, f) => (<checkbox onChange={() => handleChange(m,f)} checked={feature.checked}/>))}
      </div>
    )}
  </div>
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多