从 React JS 中的输入字段获取值

Posted

技术标签:

【中文标题】从 React JS 中的输入字段获取值【英文标题】:Getting Value from Input Field in React JS 【发布时间】:2020-09-29 16:20:58 【问题描述】:

我已经从输入字段中获取了值,但我的问题是我必须将它放到useEffect,因为我希望只有在按下它会搜索的onSearch 函数之后才能这样做。好吧,我只能使用onChange 函数从输入中获取值。当我还在打字时,它已经运行useEffect。如何从参数中获取值以将其放入输入字段,以便我刷新浏览器它仍然存在?我将如何解决这两个问题?

请在下面查看我的代码:

export default function Students() 
  const classes = useStyles();
  const dispatch = useDispatch();
  const students = useSelector((state) => state.student.students);
  const isLoading = useSelector((state) => state.student.isLoading);
  const totalPages = useSelector((state) => state.student.totalPages);
  const currentPage = useSelector((state) => state.student.currentPage);
  const itemsPerPage = useSelector((state) => state.student.itemsPerPage);
  const previous = useSelector((state) => state.student.previous);
  const next = useSelector((state) => state.student.next);
  const history = useHistory();
  const location = useLocation();
  const  search  = location;
  const params = new URLSearchParams(search);
  const page = params.has('page') ? parseInt(params.get('page')) : 1;
  const rowsPerPage = params.has('rowsPerPage') ? parseInt(params.get('rowsPerPage')) : 10;
  const [searchValue, setSearchValue] = React.useState('');

  const handleChangePage = (event, newPage) => 
    params.set('page', newPage + 1);
    history.push('/students?' + params.toString());
  ;

  const handleChangeRowsPerPage = (event) => 
    params.delete('page');
    params.set('rowsPerPage', +event.target.value);
    history.push('/students?' + params.toString());
  ;

  const onChange = (event) => 
    setSearchValue(event.target.value);
  ;

  const onSearch = () => 
    params.delete('page');
    params.delete('rowsPerPage');
    params.set('key', searchValue.toString());
    history.push('/students?key=' + searchValue.toString());
    dispatch(getStudents(10, 1, searchValue.toString()));
  ;

  useEffect(() => 
    dispatch(getStudents(rowsPerPage, page, ''));
  , [page, rowsPerPage, dispatch]);

  return (
    <div>
      <div className=classes.title>
        <h2>Students</h2>
      </div>

      <div className=classes.header>
        <Paper component="form" className=classes.searchBarSection>
          <InputBase
            className=classes.input
            placeholder="Search..."
            inputProps= 'aria-label': 'search...' 
            onChange=onChange
          />
          <IconButton type="button" className=classes.iconButton aria-label="search" onClick=onSearch>
            <SearchIcon />
          </IconButton>
        </Paper>
      </div>

      isLoading ? (
        <div style= display: 'flex', justifyContent: 'center' >
          <CircularProgress />
        </div>
      ) : students && students.length > 0 ? (
        <Paper className=classes.root>
          <TableContainer className=classes.container>
            <Table stickyHeader aria-label="sticky table">
              <TableHead>
                <TableRow>
                  <TableCell>First Name</TableCell>
                  <TableCell>Last Name</TableCell>
                  <TableCell>Actions</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                students.map((patient, index) => (
                  <TableRow key=index>
                    <TableCell>patient.FirstName</TableCell>
                    <TableCell>patient.LastName</TableCell>>
                    <TableCell>
                      <Button variant="contained" size="small" color="primary" startIcon=<VisibilityIcon />>
                        View
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              </TableBody>
            </Table>
          </TableContainer>
          <TablePagination
            rowsPerPageOptions=[10, 25, 100]
            component="div"
            count=totalPages
            rowsPerPage=itemsPerPage
            page=currentPage - 1
            backIconButtonProps=
              disabled: previous === null,
            
            nextIconButtonProps=
              disabled: next === null,
            
            onChangePage=handleChangePage
            onChangeRowsPerPage=handleChangeRowsPerPage
          />
        </Paper>
      ) : (
        <Typography variant="body2">No Students Available...</Typography>
      )
    </div>
  );

【问题讨论】:

【参考方案1】:

这里不需要useEffect

删除useEffect并更改onSearch

const onSearch = () => 
  params.delete('page');
  params.delete('rowsPerPage');
  params.set('key', searchValue.toString());
  history.push('/students?key=' + searchValue.toString());
  dispatch(getStudents(rowsPerPage, page, searchValue.toString()));
;

【讨论】:

嗨!我也在使用服务器端搜索和服务器端分页。我想我需要使用useEffect?我有我的第二个问题。刷新后,如何在输入搜索中显示它的参数?我已经更新了问题中的代码以便更好地理解

以上是关于从 React JS 中的输入字段获取值的主要内容,如果未能解决你的问题,请参考以下文章

react-hook-form 的 DefaultValues 未将值设置为 React JS 中的输入字段

react-redux,使用一个操作从两个输入字段中更改对象键/值

获取导致 React 闪烁的输入值

如何使用 React.JS 正确验证输入值?

单击时 React 输入字段的值仍然存在

如何使用 React Hooks 在另一个组件中获取表单的输入值