React Hooks-重设下拉菜单

时间:2018-12-18 18:27:30

标签: reactjs react-hooks

我正在使用React Hooks测试多个选择/选项元素。我能够从本地列表中填充下拉菜单,也可以使用axios API getter方法。最后,我创建了一个重置​​按钮,以将这些下拉值重置为原始值(例如“选择状态”和“选择作者”),但无法正常工作,我不确定重置这些值的最佳方法是什么值。

我没有在此处发布代码,而是在此处添加了指向该示例项目的链接。任何提示/指针都非常感谢。

codesanbox project link

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import StateSelector from "./StateSelector";
import Footer from "./Footer";

const SelectTesting = () => {
const reqUrl = "https://hn.algolia.com/api/v1/search?query=redux";

const initialStateValue = [{ id: 0, value: " --- Select A State --- " }];
const initialAuthorValue = [" --- Select an Author --- "];

const allowedState = [
  { id: 1, value: "Alabama" },
  { id: 2, value: "Georgia" },
  { id: 3, value: "Missisippi" }
];

const [authors, setAuthors] = useState(initialAuthorValue);
const [allStates, setAllSelected] = useState(initialStateValue);
const [stateSelected, setStateSelected] = useState(initialStateValue[0].value);

let authorComponent = null;

// useEffect to get states
useEffect(() => {
  console.log("Inside effect");
  const stateValues = initialStateValue;
  allowedState.map(sel => {
    stateValues.push(sel);
    return setAllSelected(stateValues);
  });
}, []);

// useEffect to get Authors
useEffect(() => {
  console.log("Inside effect 2");
  axios(reqUrl).then(result =>
    result.data.hits.map(res => {
      initialAuthorValue.push(res.author);
      return setAuthors(initialAuthorValue);
    })
  );
}, []);

authorComponent = (
  <select>
    {authors.map((author, index) => (
      <option key={index}>{author}</option>
    ))}
  </select>
);

const stateSelectionHandler = event => {
  const value = event.target.value;
  console.log(allStates);
  const stateIndex = allStates.findIndex(state => state.value === value);
  console.log(event.target.value, allStates, "index:", stateIndex);
  setStateSelected(event.target.value);
};

const resetClickHandler = () => {
  console.log("reset was clicked");
  setStateSelected(initialStateValue[0].value);
};

console.log("Inside Index.js Main");

return (
  <div>
    <hr />
      <StateSelector
      selectedState={stateSelected}
      allStates={allStates}
      onStateSelection={stateSelectionHandler}
      />
    <hr />
    <label>Author:</label>
    {authorComponent}
   <hr />
   <Footer onResetClick={resetClickHandler} />
  </div>
);
};

const rootElement = document.getElementById("root");
ReactDOM.render(<SelectTesting />, rootElement);

1 个答案:

答案 0 :(得分:0)

您唯一缺少的实际上是选择元素Sets

中的only value属性

但是,我认为<select onChange={onStateSelection} value={props.selectedState}>组件不需要是有状态的组件。最好使它成为受控/哑巴组件,使其仅从父级获取道具并让父级控制其值和行为。

https://codesandbox.io/s/j7zwxnn65w