【发布时间】:2019-09-18 17:10:12
【问题描述】:
我将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,它会修复它吗?
标签: javascript reactjs react-redux react-hooks