我想根据一些条件映射select选项。我尝试使用useState。下面是我尝试的代码。
但是浏览器控制台显示:-TypeError: Cannot read properties of undefined (reading 'map')页面没有显示
const[optLoanDur,setOptLoanDur]=([])
const onChangeHandler = (e) => {
console.log(e.target.value);
if(e.target.name=="loanName" && e.target.value=="Demand Loan"){
setOptLoanDur([{value:'100',label:'100'}])
}
else{
setOptLoanDur([{value:'300',label:'300'}])
}
{optLoanDur.map((option) => (
<option value={option.value}>{option.label}</option>
))}
首先。在StackOverflow上发布问题时,把问题写好是非常重要的。人们不想知道你想问什么。当你只需要一个代码块时,你有多个代码块。你有死代码,onChangeHandler
不会被使用。如果在某个地方使用了它,你应该包括它。
这不是什么大事,因为你是一个新的贡献者,但这是一项重要的技能。试着把你的问题编辑得更清晰、更有条理。
也就是说,你没有使用setState
或useState
。
正确的方法如下:
const [optLoanDur, setOptLoanDur] = useState([]);
useState
所做的是返回一个有两个参数的数组。第一个是值,第二个总是用于修改值的分派函数。调用分派函数将改变你的值,并导致你的值改变,你的函数重新呈现改变显示。这就是useState
如此重要的原因,它返回一个触发重新渲染的调度函数。
useState
的实参是一个初始化式。在本例中,我们说"给我一个值和一个分派器,将值初始化为一个空数组。">
setState
。
我希望这有助于并为您试图解决的问题提供一个很好的模板。
import React, { useState } from "react";
import "./styles.css";
export default function App() {
// initialize the loans to be empty.
const [optLoanDur, setOptLoanDur] = useState([]);
// we need some way to trigger adding loans.
// I chose to use a button as an example.
// you should be able to rework this bit
// by bit to get the behavior you want.
function onClickHandler(isLoan) {
if (isLoan) {
addLoan({ value: "100", label: "100" });
} else {
addLoan({ value: "300", label: "300" });
}
}
function addLoan(loan) {
// set the new optLoanDur to be the list of all the
// old loans, plus the new loan.
setOptLoanDur((oldLoans) => [...oldLoans, loan]);
}
// show a list of the loan options.
// also show the two buttons, who have callback
// functions to add different types of loans.
// in the list, we have to include a key prop
// with each element otherwise React does not
// know how to render them properly.
// you are technically not supposed to use an
// index, but for this example it should be ok.
// the key HAS to be UNIQUE. So you could generate
// an ID for each loan and use that instead.
return (
<React.Fragment>
{optLoanDur.map((option, idx) => (
<option value={option.value} key={idx}>
{option.label}
</option>
))}
<button onClick={() => onClickHandler(true)}>Add Loan</button>
<button onClick={() => onClickHandler(false)}>Add Not Loan</button>
</React.Fragment>
);
}