在use组件中结合useState钩子

时间:2020-04-20 15:17:10

标签: reactjs react-hooks react-state-management

我最近开始大量使用react钩子。

使用“ React.useState”时,状态管理对我来说似乎更直观。

无论如何,当它可以正常工作时,我知道开始保存到状态的更多值看起来就显得混乱了。

例如,随着我的汽车零件应用程序的进展,它现在看起来像这样:

const [isShown, setIsShown] = React.useState(false);
const [idVal, setIdValue] = React.useState(false);
const [partNameVal, setPartNameValue] = React.useState(false);
const [engineEngineEngineTypeVal, setEngineEngineTypeValue] = React.useState(false);
const [displacementVal, setDisplacementValue] = React.useState(false);
const [makeVal, setMakeValue] = React.useState(false);
const [countryVal, setCountryValue] = React.useState(false);

const hide = () => setIsShown(false);

const show = (id, partName, engineEngineType, displacement, department, country) => {
    setIsShown(true);
    setIdValue(id);
    setPartNameValue(partName);
    setEngineTypeValue(engineEngineType);
    setDisplacementValue(displacement);
    setMakeValue(department);
    setCountryValue(country);
}

<p>ID:  {idVal}</p>
<p>PartName:  {partNameVal}</p>
<p>EngineType:  {engineEngineTypeVal}</p>
<p>Displacement:  {displacementVal}</p>
<p>Make:  {makeVal}</p>
<p>Country:  {countryVal}</p>

我想知道是否有办法使它更具可读性,但仍然非常直观。

谢谢!

4 个答案:

答案 0 :(得分:3)

通常,您要处理单个对象或使用useReducer,例如:

const INITIAL_CAR = {
  id: 0,
  part: "4xE3",
  country: "USA",
  // ... More entries
};

const CarApp = () => {
  const [car, setCar] = useState(INITIAL_CAR);
  const [isShown, setIsShown] = useState(false);

  const show = (carProps) => {
    setIsShown(true);
    setCar(carProps);
  };

  const { id, part, engine, displacement, make, county } = car;

  const updateCountry = (country) =>
    setCar((prevCar) => ({ ...prevCar, country }));

  const updateCarProperty = ({ property, value }) =>
    setCar((prevCar) => ({ ...prevCar, [property]: value }));

  return (
    <div>
      {isShown && (
        <>
          <p>ID: {id}</p>
          <p>PartName: {part}</p>
          <p>EngineType: {engine}</p>
          <p>Displacement: {displacement}</p>
          <p>Make: {make}</p>
          <p>Country: {country}</p>{" "}
        </>
      )}
      // use show, updateCountry, updateProperty etc.
    </div>
  );
};

答案 1 :(得分:2)

我会说import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.*; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellReference; import java.util.GregorianCalendar; class CreateExcelTable { public static void main(String[] args) throws Exception { Object[][] data = new Object[][] { new Object[] {"Text", "Date", "Number", "Boolean"}, new Object[] {"Text 1", new GregorianCalendar(2020, 0, 1), 1234d, true}, new Object[] {"Text 2", new GregorianCalendar(2020, 1, 15), 5678d, true}, new Object[] {"Text 3", new GregorianCalendar(2020, 2, 1), 90.1234, false}, new Object[] {"Text 4", new GregorianCalendar(2020, 3, 15), 567.89, false} }; try (XSSFWorkbook workbook = new XSSFWorkbook(); FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) { XSSFCellStyle dateCellStyle = workbook.createCellStyle(); dateCellStyle.setDataFormat(14); XSSFSheet sheet = workbook.createSheet(); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellValue("Lorem ipsum"); row = sheet.createRow(1); cell = row.createCell(0); cell.setCellValue("semit dolor"); int nextRow = 3; int nextCol = 0; for (Object[] dataRow : data) { row = sheet.createRow(nextRow++); nextCol = 0; for (Object value : dataRow) { cell = row.createCell(nextCol++); if (value instanceof String) cell.setCellValue((String)value); else if (value instanceof GregorianCalendar) { cell.setCellValue((GregorianCalendar)value); cell.setCellStyle(dateCellStyle); } else if (value instanceof Double) cell.setCellValue((Double)value); else if (value instanceof Boolean) cell.setCellValue((Boolean)value); } } CellReference topLeft = new CellReference(sheet.getRow(3).getCell(0)); CellReference bottomRight = new CellReference(sheet.getRow(nextRow-1).getCell(3)); AreaReference tableArea = workbook.getCreationHelper().createAreaReference(topLeft, bottomRight); XSSFTable dataTable = sheet.createTable(tableArea); //dataTable.setName("Table1"); dataTable.setDisplayName("Table1"); //this styles the table as Excel would do per default dataTable.getCTTable().addNewTableStyleInfo(); XSSFTableStyleInfo style = (XSSFTableStyleInfo)dataTable.getStyle(); style.setName("TableStyleMedium2"); style.setShowColumnStripes(false); style.setShowRowStripes(true); //this sets auto filters dataTable.getCTTable().addNewAutoFilter().setRef(tableArea.formatAsString()); workbook.write(fileout); } } } 钩就是这种情况。

https://reactjs.org/docs/hooks-reference.html#usereducer

useReducer

答案 2 :(得分:1)

您可以创建一个新文件,以从组件中提取所有挂钩逻辑。

例如致电<s:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <RequestHeaderResponse> {{DATA}} </RequestHeaderResponse> <SearchPolicyDetailsResponse> {{DATA}} </SearchPolicyDetailsResponse> </s:Body> </s:Envelope>

useHooks.js

这里的想法是将所有的钩子逻辑放入函数中并返回JSX内部所需的值。

然后在您的组件中导入并使用从useHooks导出的所有属性

export default () => {
const [isShown, setIsShown] = React.useState(false);
const [idVal, setIdValue] = React.useState(false);
const [partNameVal, setPartNameValue] = React.useState(false);
const [engineEngineEngineTypeVal, setEngineEngineTypeValue] = React.useState(false);
const [displacementVal, setDisplacementValue] = React.useState(false);
const [makeVal, setMakeValue] = React.useState(false);
const [countryVal, setCountryValue] = React.useState(false);

const hide = () => setIsShown(false);

const show = (id, partName, engineEngineType, displacement, department, country) => {
    setIsShown(true);
    setIdValue(id);
    setPartNameValue(partName);
    setEngineTypeValue(engineEngineType);
    setDisplacementValue(displacement);
    setMakeValue(department);
    setCountryValue(country);
}

return [isShown, idVal, partNameVal, engineEngineEngineTypeVal, displacementVal, 
makeVal, countryVal, show, hide];
}

希望这个想法很明确

答案 3 :(得分:1)

我在一个组件中处理大部分状态的方式是使用一个useState,那样它只是一个大对象。

这是一个小例子:

const [state, setState] = useState({
  num: 1,
  cars: ['volvo', 'mazda'],
  john: {name: 'John', last: 'Foo'}
})

如果您要更改某些内容,我通常会使用此功能

const onChange = (name, value) => {
  setState(prevState => ({...prevState, [name]: value}))
}

这会将键name更改为值value。这在我眼中更加清晰。