下面是我的react项目中的一个组件示例:
import {useState, useEffect, useRef} from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { createWorker } from '../../actions/worker';
import '../components.scss';
const New = () => {
const [worker, setWorker] = useState(
{
name: "",
email: "",
confirmation_email: "",
admin: false
}
);
const [checked, setChecked] = useState(false); //Determines if admin checkbox is checked or not
const [successMessage, setSuccessMessage] = useState(null); //If there's a success in the uploading process, we simply will put a message at the bottom.
const dispatch = useDispatch();
const errors = useSelector((state) => state.errors.error);
const selectedWorker = useSelector((state) => state.workers.current_worker); //We will be using this to determine if the user has a right to access this page
const renderedAlreadyRef = useRef(false); //Let's us know if we've rendered it already or not
useEffect(() => {
//We'll be using this to see if allWorkers.workers has been updated. We also use the ref renderedAlreadyRef to ensure it only runs after rendering
if (renderedAlreadyRef.current === true && Object.keys(errors).length === 0){
setSuccessMessage("Worker created successfully");
}
}, [errors])
const handleSubmit = (e) => {
//Handles submitting the form
e.preventDefault();
dispatch(createWorker(worker));
renderedAlreadyRef.current = true;
}
const handleChange = (e) => {
const newKey = e.target.id;
const newValue = e.target.value
if (newKey === "admin"){
setChecked(!checked)
setWorker(oldState => ({...oldState, "admin": !checked}))
}
else{
setWorker(oldState => ({ ...oldState, [newKey]: newValue}));
}
}
if (Object.keys(selectedWorker).length !== 0){
if (selectedWorker.admin === 1){
return(
<>
<form id="worker_form" onSubmit={e => handleSubmit(e)}>
<label>
Worker Name:
<input type="text" defaultValue={worker.name} id="name" onChange={e => handleChange(e)}></input>
</label>
<label>
Worker Email:
<input type="text" defaultValue={worker.email} id="email" onChange={e => handleChange(e)}></input>
</label>
<label>
Confirmation Email:
<input type="text" defaultValue={worker.confirmation_email} id="confirmation_email" onChange={e => handleChange(e)}></input>
</label>
<label>
Are they an admin?: <input type="checkbox" checked={checked} id="admin" onChange={e => handleChange(e)} />
</label>
<button type="submit" onClick={e => handleSubmit(e)} className="submit_new_button">Submit</button>
</form>
<h3 className='new_messages'>{successMessage}</h3>
</>
)
}
else{
return(
<div id="Forbidden">
<h1>Error 403 - Forbidden</h1>
<h2>You do not have access to this page</h2>
</div>
)
}
}
else{
return(<h1>Loading...</h1>)
}
}
export default New;
直到昨天,这是完美的工作,但从昨天开始,突然,有条件渲染的东西不再工作。他们只是永远加载...这是除非我改变文件中的东西(甚至只是添加一点空白),然后保存该文件。(在这个组件中,没有改变的是successMessage)。我不知道是什么原因导致了这个问题,因为我昨天改变了很多东西。如果你有任何想法,请告诉我,因为这让我很困惑。
1条答案
按热度按时间insrf1ej1#
我发现了这一点。原来使用refs是发生这种情况的原因。我假设基于refs的工作方式,它不会在它们更改后重新呈现页面(我想这是有道理的,因为它们也不会触发useEffects)。