如果我的组件与以下相似:
import React, { useState } from "react";
import ReactDOM from "react-dom";
function calculateNewValueAndMaybeError(test) {
try {
// do something with test that might error
// const newTest = functionThatMightError(...)
// if it doesn't error, return { value: newTest, error: '' }
} catch (err) {
// is it correct to now return this in case of error?
// return { value: test.value, error: 'Something went wrong' }
}
}
function App() {
const [test, setTest] = useState({ value: "", error: "" });
return (
<div>
<p>Test: {test.value}</p>
<p>Error: {test.error}</p>
<button onClick={() => setTest(calculateNewValueAndMaybeError(test))}>
Click me
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
我有一个按钮,该按钮应突变我的变量称为test
的状态,是否有一种方法可以处理错误,而无需始终将值和错误的对象传递给对象?
否则,这是否会导致必要的代码有时会喜欢以下:
onChange={() => setTest({ value: e.target.value, error: test.error })}
您想更新test.value
的值,但保留test.error
的值。
我觉得我很明显。
谢谢!
有必要合并两个状态,表明它们应该作为不同的状态处理:
function App() {
function calculateNewValueAndMaybeError(test) {
try {
...
setValue(...);
setError(null);
} catch (err) {
setError('Something went wrong');
}
}
const [error, setError] = useState(null);
const [value, setValue] = useState('');
return (
<div>
<p>Test: {value}</p>
<p>Error: {error}</p>
<button onClick={() => setTest(calculateNewValueAndMaybeError(test))}>
Click me
</button>
</div>
);
}
或自定义状态钩可用于合并error
字段:
const useErrorState = initialState => {
const [state, setState] = useState({ ...initialState, error: null });
const setErrorState = useCallback(stateUpdater => {
if (typeof stateUpdater === 'function') {
setState(state => {
try {
return {error: null, ...stateUpdater(state) };
} catch (error) {
return {...state, error };
}
});
} else {
setState({error: null, ...stateUpdater });
}
}, []);
return [state, setErrorState];
}
另一种可能性是将错误处理转移到父组件(可能具有高阶组件)并在那里捕获错误。