请教:react setState 以后 不 re-render

r
repast
楼主 (未名空间)

上传了图片以后,uploadFile() 能成功返回 a url to the image,
可是页面不会显示新的图片(imgUrl), 这是为什么?怎么fix这个问题?

const [imgUrl, setImgUrl] = useState('');
...

const uploadFile = async () => {
// uploading a file to S3 and get back an url

// this does not work either
//setImgUrl(url);

// hence try returning it and set it in the onChange
return url;
};

return <>
name=".."
id="id"
type="file"
onChange={() => {
uploadFile().then((url)=>setImgUrl(url));
})
/>
;

r
repast


【 在 repast (xebec) 的大作中提到: 】
: 上传了图片以后,uploadFile() 能成功返回 a url to the image,
: 可是页面不会显示新的图片,这是为什么?
: {code}
: : name=".."
: id="id"
: type="file"
:
: />
: {code}
: ...................

r
repast

哦,把 uploadFile 写成 component, url 整成里面的一个 state,
用 customized hookhttps://dev.to/vinodchauhan7/react-hooks-with-async-await-1n9g

【 在 repast (xebec) 的大作中提到: 】
: 上传了图片以后,uploadFile() 能成功返回 a url to the image,
: 可是页面不会显示新的图片(imgUrl), 这是为什么?怎么fix这个问题?
: const [imgUrl, setImgUrl] = useState('');
: ...
: const uploadFile = async () => {
: // uploading a file to S3 and get back an url
: // this does not work either
: //setImgUrl(url);
: // hence try returning it and set it in the onChange
: return url;
: ...................