我试图仅调用useState对象的一部分。
我尝试做objectName.objectValue
const [form, setForm] = useState({
firstNum: '',
secondNum: ''
})
const [Sum, setSum] = useState('')
const [isSubmitted, setSubmitted] = useState(false)
const [Operator, setOperator] = useState(null)
function handleOperator() {
const f = [form.firstNum]
const l = [form.secondNum]
const Plus = f + l
const Minus = f - l
const Multiply = f * l
const Divide = f / l
switch (Operator) {
case 'plus':
return setSum(Plus), setSubmitted(false)
case 'minus':
return setSum(Minus), setSubmitted(false)
case 'multiply':
return setSum(Multiply), setSubmitted(false)
case 'divide':
return setSum(Divide), setSubmitted(false)
default:
return null
}
}
我希望他们没有错误,但是却得到了“ firstNum未定义”
答案 0 :(得分:0)
问题一定在其他地方,可以使用useState挂钩将状态设置为对象:
const App = () => {
const [form, setForm] = React.useState({firstName: 'Foo', lastName: 'Bar'})
console.log(form, form.firstName);
const handleChange = prop => e => setForm({
...form,
[prop]: e.target.value
})
return (<p>
My name is
<br/>
<input type="text" value={form.firstName} onChange={handleChange('firstName')}/>
<input type="text" value={form.lastName} onChange={handleChange('lastName')}/>
</p>)
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>