簡體   English   中英

React useEffect鈎子-使用ID的Redux動作的無限循環

[英]React useEffect hook - infinite loop with redux action that uses ID

我將useEffect與減少動作結合使用。 我知道我必須從道具中提取動作函數,並將其作為第二個參數提供,該參數通常適用於批量獲取。 但是,如果我也使用道具中的ID,它最終會陷入無限循環:

export function EmployeeEdit(props) {
  const { fetchOneEmployee } = props;
  const id = props.match.params.id;
  const [submitErrors, setSubmitErrors] = useState([]);

  useEffect(() => fetchOneEmployee(id), [fetchOneEmployee, id]);

  const onSubmit = employee => {
      employee = prepareValuesForSubmission(employee);
      props.updateEmployee(employee._id, employee)
          .then( () => props.history.goBack() )
          .catch( err => setSubmitErrors(extractErrors(err.response)) );
  };

  return (
    <div>
        <h3>Edit Employee</h3>
        <NewEmployee employee={props.employee} employees={props.employees} onSubmit={onSubmit} submitErrors={submitErrors} />
    </div>
  )
}

EmployeeEdit.propTypes = {
  fetchOneEmployee: PropTypes.func.isRequired,
  employees: PropTypes.array.isRequired,
  employee: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  employees: state.employees.items,
  employee: state.employees.item
})

export default connect(mapStateToProps, { fetchOneEmployee, updateEmployee })(EmployeeEdit);

和redux動作:

export const fetchOneEmployee = (id) => dispatch => {
   axios.get(`http://localhost:8888/api/users/${id}`)
    .then(res => {
                const employee = res.data;
                dispatch({
                    type: FETCH_ONE_EMPLOYEE,
                    payload: employee
                })
        })
});

};

有人知道我在做什么錯嗎?

您的依賴項數組( [fetchOneEmployee, id] )中的值之一正在更改。 用您提供的有限代碼很難說出它的價值。

乍看之下,您可能希望在數組中使用fetchOne而不是fetchOneEmployee

您的inifite循環可能是由於將fetchOneEmployee作為參數傳遞給useEffect引起的。 您是否將fetchOneEmployee作為箭頭函數傳遞給EmployeeEdit? 如果您這樣做了,那么fetchOneEmployee總是會被更改。

這是有關react hooks fetch data的偉大文章的一部分。

https://www.robinwieruch.de/react-hooks-fetch-data

我特別推薦標題CUSTOM DATA FETCHING HOOK

暫無
暫無

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

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