簡體   English   中英

如何在反應中將對象映射到對象數組以進行選擇搜索?

[英]how to map object into array of objects for selectsearch in react?

所以我想將鍵和值映射到一個數組中用作選擇搜索選項,我嘗試過選擇並且它通過單獨映射每個項目來工作,現在我需要將所有數據映射到一個數組中。 我怎么能那樣做?

從api獲取數據:

export default function Dashboard() {
  
const [value, setValue] = useState();
  const [students, setstudents] = useState([]);
  useEffect(() => {
    const fetchStudents = async () => {
      try {
        const resp = await Axios({
          method: "GET",
          url: "https://jsonplaceholder.typicode.com/users",
          headers: {
            "Content-Type": "application/json",
          },
        });
        setstudents(resp.data);
      } catch (err) {}
    };
    fetchStudents();
  }, []);
  const classes = useStyles();
  

const courses=students=>{return students.map(student=>[
  <a
  href={`http://localhost:3000/teacher/course/:${student.id}`}
>
  {student.id}
</a>]);
}// tried to map into an array of links not working

制作選擇選項的下拉框,效果很好:

 <select
          onChange={e => setValue(e.currentTarget.value)}>
      {students.map(student => 
        <option key={student.id} value={student.username}>
          {student.id}
        </option>
      )}
    </select>//worked here 

當我使用 selectsearch 時,無法弄清楚如何將鍵和值映射到一個數組中,因為 selectsearch 將選項作為鍵和值的數組而不是 select:

<SelectSearch
      name="form-field-name"
      value={this.state.value}
      onChange={this.handleChange}
      clearable={this.state.clearable}
      />
      {students.map(student => 
        <options key={student.id} value={student.username}>
          {student.id}
        </options> )} //couldnt figure out how to make the array of options into single constant 

這應該工作

const courses=()=>students.map(student=>
  <a
  href={`http://localhost:3000/teacher/course/:${student.id}`}
  >
  {student.id}
</a>);

另外,如果您不想創建單獨的函數,那么

export default function App() {
  const students = [];

  return (
    <div className="App">      
      {students.map(student=>
      <a href={`http://localhost:3000/teacher/course/:${student.id}`}>
        {student.id}
      </a>)}
    </div>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM