我得到了SchoolsList组件的以下代码:
import { useSelector } from "react-redux"
import ClassesList from "../classes/ClassesList"
const SchoolsList = () => {
const schools = useSelector(selectAllSchools)
if (schools.length === 0) {
return <h2>No schools created yet</h2>
}
let selectedSchool = schools[0]
const handleChange = (e) => {
selectedSchool = schools[e.target.value]
document.getElementById("schoolName").innerText = "Name: " + selectedSchool.name
}
return (
<div className='SchoolsList'>
<select onChange={handleChange}>
{schools.map((school, id) => <option key={id} value={id}>{school.name}</option>)}
</select>
<h3>Selected school</h3>
<h4 id="schoolName">Name: {selectedSchool.name}</h4>
<ClassesList classes={selectedSchool.classes} />
</div>
)
}
export default SchoolsList
当select的值更改,变量selectedSchool更改时,ClassesList组件道具不会更新。我对react reduce还很陌生,所以我有点不知所措。当选择发生变化时,我该如何更新道具的值?
您的变量selectedSchool
不是被动的,您可以使用钩子useState
,它将在props中更新状态。示例:
const [setSelectedSchool, selectedSchool] = useState(schools[0]);
const handleChange = (e) => {
setSelectedSchool(schools[e.target.value])
}
此外,你不需要这样做document.getElementById("schoolName").innerText = "Name: " + selectedSchool.name
,这是不正确的。
您已经有正确的JSX<h4 id="schoolName">Name: {selectedSchool.name}</h4>
这是因为没有发生重新渲染。请尝试使用useState或useRef挂钩来存储所选学校的值。
const [state, setState] = useState({
selectedSchool:''
})
然后保存州内所选学校的值。使用useEffect将状态设置为所选学校的初始值。
useEffect(()=>{
setState({...state, selectedSchool:schools[0]})
},[])