【发布时间】:2019-09-07 20:46:43
【问题描述】:
IMO,React Hooks useState 非常适合从 props 中选择使用 value 或使用自己的 state 的模式,但是当我有条件地使用 hook 时,lint 显示了一些错误。
我尝试使用条件如下的钩子,但出现 eslint 错误 React hook useState is called conditionally。根据这个explanation from doc,React relies on the order in which Hooks are called。
const Counter = ({ value, onChange, defaultValue = 0 }) => {
const [count, onCountChange] =
typeof value === "undefined" ? useState(defaultValue) : [value, onChange];
return (
<div>
{count.toString()}
<button
onClick={() => {
onCountChange(count + 1);
}}
>
+
</button>
</div>
);
};
function App() {
const [count, onCountChange] = useState(0);
return (
<div className="App">
<div>
Uncontrolled Counter
<Counter />
</div>
<div>
Controlled Counter
<Counter value={count} onChange={onCountChange} />
</div>
</div>
);
}
如何使用钩子来实现与以下类 Component 相同的功能?
class CounterClass extends React.Component {
state = {
value: this.props.defaultValue || 0
};
render() {
const isControlled = typeof this.props.defaultValue === "undefined";
const count = isControlled ? this.props.value : this.state.value;
return (
<div>
{count.toString()}
<button
onClick={() => {
isControlled &&
this.props.onChange &&
this.props.onChange(this.props.value + 1);
!isControlled && this.setState({ value: this.state.value + 1 });
}}
>
+
</button>
</div>
);
}
}
或者这种 props/state 在一个组件中的可选方式是错误的?
我从 React JSX <input> 组件中学习了 "defaultValue"、"value"、"onChange" API 命名和想法。
【问题讨论】:
标签: reactjs react-hooks