繁体   English   中英

如何使用 React Hooks 在 map function 内动态和有条件地渲染 select 选项

[英]How to dynamically and conditionally render select options inside of a map function using React Hooks

我无法让这个下拉列表有条件地和动态地呈现在已经动态呈现的表中。 我在codepen中重新创建了它:

https://codepen.io/e0marina/pen/WNpvxJo?editors=0011

我尝试了很多事情,包括将 function 内联,这导致列表中的项目太多。 然后我尝试清除每个循环顶部的列表,但它没有在每个下拉列表中放置足够的项目。 在 resultArr 上的 useState 中尝试了 setDropOptions,这变成了无限循环。

无论如何,我被困住了,不胜感激!

我对钩子有点陌生,并且编码不到一年,所以请记住这一点:)


function Test() {
  const [data, setData] = React.useState([]);

  const [dropOptions, setDropOptions] = React.useState([1, 2, 3, 4, 5, 6, 7]);

  const handleDropListOrder = (incoming) => {
      //take existing (incoming) option out of the array from below in render func, item.id
      let resultArr = dropOptions.filter((option) => option != incoming);
      //put the existing one at the 0 position in array
      resultArr.unshift(incoming);
    
    // why does this cause a problem? Too many loops on render?
     resultArr.foreach ((el) => return <option>{el}</option>);
    
  };
  
  

  //calls API
  React.useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

  //console.log(data);

  return (
    <div>
      {data.map((item) => (
        <tr key={item.id}>
          <td className="px-6 py-3 whitespace-nowrap text-sm font-medium text-gray-900">
            <h2>TITLE</h2>
            {item.title}
          </td>
          <td className="px-6 py-3 whitespace-nowrap text-sm font-medium text-gray-900">
            <h2>BODY</h2>
            {item.body}
          </td>
          <td className="px-6 py-3 whitespace-nowrap text-sm text-gray-500">
            <select className="p-1">
              {handleDropListOrder(item.id)}
            </select>
          </td>
        </tr>
      ))}
    </div>
  );
}

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <Test />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
  • handleDropListOrder()return任何内容。

  • foreach()不是 function,它被命名为forEach() 但是你会在这里想要map()

  • (el) => return <option>{el}</option>是语法错误。

    它应该是(el) => <option>{el}</option>(el) => { return <option>{el}</option>; } (el) => { return <option>{el}</option>; }

全部一起:

const handleDropListOrder = (incoming) => {
  //take existing (incoming) option out of the array from below in render func, item.id
  let resultArr = dropOptions.filter((option) => option != incoming);
  //put the existing one at the 0 position in array
  resultArr.unshift(incoming);

  return resultArr.map((el) => <option>{el}</option>);
};

暂无
暂无

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

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