I know this question has been asked by many people, but I tried the method mentioned, but it still didn't work。 Here is my code
let tmp:any = {
"title": "Product Set",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "number"
},
"money": {
"type": "string"
}
}
}
const SForm = () => {
const { projectId } = useParams() as { projectId: string }
const [schema , setSchema] = useState(tmp);
async function getData(id: number) {
const { data } = await http.post('/project/testparam', {
project_id: id,
})
return data.data
}
setSchema(getData( projectId))
return (
<Form schema = {schema as JSONSchema7}
>
</Form>
)
}
Many people say the reason is:everything between the curly braces gets evaluated immediately. use arrow function.
setSchema(()=> {
getData( projectId)
})
But it doesn't work
CodePudding user response:
You are setting the schema on every render. Calling a setState
hook triggers a render.
What is happening is as follows:
intialRender -> setSchema -> re-render -> setSchema -> re-render -> ...
You likely want to only get a schema once for a projectId:
const schema = useMemo(() => getData( projectId), [getData, projectId])
CodePudding user response:
put the function inside a useEffect function so it runs once at render time
useEffect(() => {
setSchema(getData( projectId))
}, [/* dependencies */])
the dependencies box is to pass params that will run the useEffect everytime that param is re-rendered