反应:使用 useReducer 和功能组件将 api 结果放入表中

Neo*_*Neo 5 reactjs react-hooks use-reducer

我是全新的反应。我已经正式完成用头撞墙了。我就是想不通。这是我的情况:

我正在尝试将 API 调用的结果放入表中。我已调用 API 工作并返回结果。我被困在如何使用返回的数据更新我的数组。完成后,我可以用数据填充表格(至少在逻辑上这是我的大脑告诉我的方式)。

初始表单状态设置:

const initialFormState = {
    fileTypeId : '',
    companyMasterId: '',
    investmentCompanyId: '',
    startDate: '',
    endDate: '',
    result: '',
    fileLogs: []
}
Run Code Online (Sandbox Code Playgroud)

以上所有字段都是表单\数据库中的字段。API 调用采用这些参数来调用存储过程,该过程根据搜索参数返回结果集。fileLogs[] 是我想放置返回数据的地方。我不确定是否需要将它从这个设置中移出并使用 useState 作为一个单独的东西?

减速器初始化:

 const [formState, dispatch] = useReducer (formReducer, initialFormState)
Run Code Online (Sandbox Code Playgroud)

减速机设置

formReducer.js

import actionTypes from "./actionTypes"

const formReducer = (state, action) => {
    switch (action.type) {
        case actionTypes.handle_input_text:
            return {
                //using the spread operator (…state) to copy across all the properties and values from the state object. 
                //then we can modify the values of specific state properties by explicitly declaring them again with a new value.
                ...state,
                [action.field]: action.payload,
            }
        case actionTypes.toggle_consent:
            return{
                ...state,
                hasConsented: !state.hasConsented
            }
        case actionTypes.on_success:
            return{...state, filelogs: action.payload}     
        default:
            return state
    }
}
export default formReducer
Run Code Online (Sandbox Code Playgroud)

API调用

function getFileRouteLogs (e)  {
        e.preventDefault()

        apiService.getFileRouteLogs(
            formState.fileTypeId,
            formState.companyMasterId,
            formState.investmentCompanyId,
            formState.startDate,
            formState.endDate,
            formState.result
        )
         .then((response)=>{
            //  dispatch({
            //     type: actionTypes.on_success,
            //     // payload: [...formState.fileLogs,  response.data]
            //     payload: response.data
            //     })
            formState.fileLogs = response.data
            console.log(response.data)
        }) 
Run Code Online (Sandbox Code Playgroud)

表单输入更改的处理程序

const handleInputChange = (e) => {
        dispatch({
            type: actionTypes.handle_input_text,
            field: e.target.name,
            payload: e.target.value
        })
    }
Run Code Online (Sandbox Code Playgroud)

输入表格

return (
            <div>
                <h1>File Route Log Search</h1>
                <hr />
                <h2>Form field area</h2>
                <Form onSubmit={getFileRouteLogs}>
                    <FormGroup row>
                        <Label for="fileTypeId" sm={2}>FileTypeId</Label>
                        <Col sm={2}>
                            <Input  type="text" name="fileTypeId" value={formState.fileTypeId} onChange={(e) => handleInputChange(e)}></Input>
                        </Col>
                    </FormGroup>
                    <FormGroup row>
                        <Label for="companyMasterId" sm={2}>CompanyMasterId</Label>
                        <Col sm={2}>
                            <Input id="companyMasterId" type="text" name="companyMasterId" value={formState.companyMasterId} onChange={(e) => handleInputChange(e)} ></Input>
                        </Col>
                    </FormGroup> 
...
Run Code Online (Sandbox Code Playgroud)

尝试设置表来保存数据

const FileRouteLogTable = ({formState}) => {
  return (
    <table className="table">
      <thead>
        <tr>
          <th>FileRouteLogId</th>
          <th>CompanyMasterId</th>
          <th>FileTypeId</th>
          <th>Result</th>
          <th>InvestmentCompanyMasterId</th>
          <th>FileName</th>
        </tr>
      </thead>
      <tbody>
      { (formState.length > 0) ? formState.map( (form, index) => {
           return (
            <tr key={ index }>
              <td>{ form.fileRouteLogId }</td>
              <td>{ form.companyMasterId }</td>
              <td>{ form.fileTypeId}</td>
              <td>{ form.result }</td>
              <td>{ form.investmentCompanyMasterId }</td>
              <td>{ form.fileName }</td>
            </tr>
          )
         }) : <tr><td colSpan="5">Enter search parameters...</td></tr> }
      </tbody>
    </table>
  );
}

export default FileRouteLogTable
Run Code Online (Sandbox Code Playgroud)

我打算尝试使用反应表,但在我可以做任何表的事情之前我被困在更新数据上

import { useTable } from 'react-table'
function FileRouteLogTable({ columns, formState }) {
    // Use the state and functions returned from useTable to build your UI
    const {
      getTableProps,
      getTableBodyProps,
      headerGroups,
      rows,
      prepareRow,
    } = useTable({
      columns,
      formState,
    })
  
    return (
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map(headerGroup => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column => (
                <th {...column.getHeaderProps()}>{column.render('Header')}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.map((row, i) => {
            prepareRow(row)
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map(cell => {
                  return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                })}
              </tr>
            )
          })}
        </tbody>
      </table>
    )
  }
  export default FileRouteLogTable
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。我查看的所有示例都没有我的综合因素:

  • 功能组件
  • 使用 useReducer
  • 使用 axios
  • 一切都不在一页上
  • 不使用 useEffect 在页面加载时调用 API GET
  • 不只是在控制台日志中显示结果

更新 我修复了@johanchopin 提到的大小写问题并更改了有效负载。我仍然没有表中的任何数据,所以我将表逻辑从:

 { (formState.length > 0) ? formState.map( (form, index) => {
Run Code Online (Sandbox Code Playgroud)

 { (formState.fileLogs.length > 0) ? formState.fileLogs.map( (form, index) => {
Run Code Online (Sandbox Code Playgroud)

数据在表中

joh*_*pin 4

对你来说可悲的是,这似乎是一个简单的拼写错误问题fileLogsformReducer在您分配action.payloadfilelogs而不是的函数中fileLogs。进行此更新后,您可以再次使用该dispatch功能:

    .then((response) => {
      dispatch({
        type: actionTypes.on_success,
        payload: response.data
      });
    });
Run Code Online (Sandbox Code Playgroud)

查看现场示例:

编辑奇怪的伽利略w59fg