函数内的变量集未在其他函数中定义
Variable set within function not defined in other function
我正在使用 react.js,我有以下代码。
function App() {
let Submitable;
const [values, setValues] = useState([])
//...
onTicket.save = () => {
console.log(Submitable) // logs undefiened
if (Submitable) {
return true
} else {
return `Please fill out the following fields before submitting:${values.map(el => ` ${el.name}`)}`
}
})
useEffect(() => {
if (values.length === 0) {
Submitable = true
//enableSave
} else {
Submitable = false
//disableSave
}
}, [values])
return (
<>
///jsx code block
</>
);
}
export default App;
我认为在 useEffect 函数中将 Submitable 设置为 true 或 false,该值将传递给其他函数,但在调用时,Submitable 记录未定义。如果我尝试将 Submitable 作为参数传递,它也会记录 undefined.
来自 useEffect
内部的分配将在每次渲染时丢失。要随着时间的推移保留值,请将其存储在 useRef
挂钩中,并将可变值保留在 current
属性
中
const Component = () =>{
const submitable = useRef()
useEffect(() =>{
submitable.current = 'foo'
},[])
console.log(submitable.current) // 'foo'
}
我正在使用 react.js,我有以下代码。
function App() {
let Submitable;
const [values, setValues] = useState([])
//...
onTicket.save = () => {
console.log(Submitable) // logs undefiened
if (Submitable) {
return true
} else {
return `Please fill out the following fields before submitting:${values.map(el => ` ${el.name}`)}`
}
})
useEffect(() => {
if (values.length === 0) {
Submitable = true
//enableSave
} else {
Submitable = false
//disableSave
}
}, [values])
return (
<>
///jsx code block
</>
);
}
export default App;
我认为在 useEffect 函数中将 Submitable 设置为 true 或 false,该值将传递给其他函数,但在调用时,Submitable 记录未定义。如果我尝试将 Submitable 作为参数传递,它也会记录 undefined.
来自 useEffect
内部的分配将在每次渲染时丢失。要随着时间的推移保留值,请将其存储在 useRef
挂钩中,并将可变值保留在 current
属性
const Component = () =>{
const submitable = useRef()
useEffect(() =>{
submitable.current = 'foo'
},[])
console.log(submitable.current) // 'foo'
}