我正在将一个函数从父组件传递给子组件,该函数将更新状态父组件中的值。传递工作正常,在子组件中我可以访问该函数,但是当我尝试更改时,单击按钮并调用“ handleAddClass”函数时,该值不会更改。发送到API的数据也可以正常工作。
在子项中更新值时,父项中的h1 {setupProgressTeacher.classesByTeacher} / h1不会更改。
父组件
import React, { useLayoutEffect, useCallback, useState, useContext } from 'react';
import { Container } from './styled';
import Navbar from '../../components/NavBar';
import AddClass from '../TeacherSetup/addclass';
import api from '../../services/api';
interface TeacherSetupState {
classesByTeacher: number;
}
const Dashboard: React.FC = () => {
const [setupProgressTeacher, setSetupProgressTeacher] = useState<TeacherSetupState>(() => {
const classesByTeacher = 1;
return { classesByTeacher } as TeacherSetupState;
});
const updateStateProgress = useCallback((classesByTeacher: number) => {
setSetupProgressTeacher({ classesByTeacher });
}, []);
useLayoutEffect(() => {
async function fetchData() {
const token = localStorage.getItem('@Ensae:token');
const response = await api.get('/class/classbyteacher', {
headers: {
'Authorization': `Bearer ${token}`
}
});
}
fetchData();
}, []);
return (
<Container>
<Navbar />
<h1>{setupProgressTeacher.classesByTeacher}</h1>
<AddClass setProgress={(({ classesByTeacher: any }) => updateStateProgress)} />
{/* <AddSubject /> */}
</Container >
);
};
export default Dashboard;
子组件
import React, { useRef, useCallback } from 'react';
import { Content } from './styled';
import { Form } from '@unform/web';
import api from '../../services/api';
import { SiGoogleclassroom } from 'react-icons/si';
import { FormHandles } from '@unform/core';
import Input from '../../components/Form/input';
import Button from '../../components/Button';
interface AddClassData {
class_name: string;
}
interface TeacherSetupState {
setProgress: ({ classesByTeacher }: { classesByTeacher: any }) => void;
}
const AddClass: React.FC<TeacherSetupState> = (props) => {
const formRef = useRef<FormHandles>(null);
const handleAddClass = useCallback(async (data: AddClassData) => {
const userStoraged = localStorage.getItem('@Ensae:user');
let userObject;
if (typeof userStoraged === 'string') {
userObject = JSON.parse(userStoraged);
}
const dataForApi = {
class_name: data.class_name,
lesson_frequency: "Semanal",
teacher_id: userObject.id,
}
try {
await api.post('/class', dataForApi);
} catch (err) {
}
props.setProgress({ classesByTeacher: 4 });
}, [props]);
return (
<Content>
<h2>Agora que fez o primeiro login, está na hora de criar uma turma</h2>
<Form ref={formRef} onSubmit={handleAddClass}>
<div className="inputClassName" >
<Input name="class_name" className="inputAddClass" icon={SiGoogleclassroom} placeholder="O nome da turma" />
<Button type="submit">Continuar</Button>
</div>
</Form>
</Content>
);
};
export default AddClass;
答案 0 :(得分:1)
问题在于此行:
<AddClass setProgress={(({ classesByTeacher: any }) => updateStateProgress)} />
setProgress
是一个函数,它接受一个包含classesByTeacher
的对象的参数,然后不使用该参数。
您要使用该参数致电 updateStateProgress
。请注意,({ classesByTeacher: any }) =>
实际上意味着我们在解构属性时将属性classesByTeacher
的值重命名为名为any
的变量,而不是在注释类型。
<AddClass
setProgress={({ classesByTeacher }) => updateStateProgress(classesByTeacher)}
/>
您还可以仅传递updateStateProgess
函数,但是您需要相应地更改AddClass
道具的界面。