reactjs - FileReader - 如何在商店更新后更新本地状态?

标签 reactjs redux filereader

我正在玩弄食物识别 API。

我有一个名为 ingredients 的本地状态组件。

在组件中,我有一个 input 标签,它接受文件图像上传并调用 cameraHandler 方法 onChange。该方法使用FileReader将图片转为Base64

一旦 FileReader 完成图像编码,该方法调用 redux 操作 fetchIngredientsFromImage 将 base64 图像发布到路由以触发 API 调用(分析图像中的成分) .

响应被发送回前端,用于更新store。

基本上,API 调用成功了,我得到了我需要的数据,存储也成功更新了。太好了。

但我还需要做的是更新我的本地 ingredients 状态。但是我不知道如何在调用 setState 之前等待商店更新。

我已经尝试使用 if(this.props !== prevProps) methodToUpdateLocalState() 进行 componentDidUpdate,但这不起作用,因为出于某种原因组件不会在存储后重新呈现已更新.. 结果是 componentDidUpdate 中的所有内容都先运行,然后再更新存储。我觉得也没有必要(可能)。

我也尝试了 .then 等待读者在 cameraHandler 中,但是 .then 是未定义的。

如果我能得到任何意见,我将不胜感激。在这里真的很茫然,因为我有数据,我只需要以某种方式获取它以便我可以设置状态。

组件

class RecipesSearch extends Component {
  state = {
    ingredients: [], //need to update this after store is updated, but how?
  };

  cameraHandler = async (event) => {
    const { fetchIngredientsFromImage } = this.props;
    const file = event.target.files[0];
    const reader = new FileReader();
    await reader.readAsDataURL(file);
    reader.onloadend = async () => {
      const imgBase = reader.result.replace(/^data:image\/(.*);base64,/, '');
      await fetchIngredientsFromImage(imgBase); //.then here is undefined
    };
  };

render(){
  <input
    className="form-check-input"
    type="file"
    name="camera"
    accept="image/*"
    onChange={this.cameraHandler}
  />
}

Action

const fetchIngredientsFromImage = (imgBase) => async (dispatch) => {
  const { data } = await axios.post(`/api/camera/`, { imgBase });
  return dispatch(setIngredientsFromCamera(data)); //successfully updates store
};

最佳答案

作为解决方法,我在 cameraHandler 中调用了 axios.post。对此并不感到自豪,因为我想利用商店并使其与我的其他方法保持一致,但我猜暂时它会这样做。

cameraHandler = async (event) => {
    // const { loadIngredientsFromImage } = this.props;
    const file = event.target.files[0];
    const reader = new FileReader();
    await reader.readAsDataURL(file);
    reader.onloadend = async () => {
      const imgBase = reader.result.replace(/^data:image\/(.*);base64,/, '');
      await axios
        .post(`/api/camera/`, { imgBase })
        .then((response) => this.setState({ ingredients: response.data }));
    };
  };

关于reactjs - FileReader - 如何在商店更新后更新本地状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63947958/

相关文章:

JavaScript 从要上传的 FileList 中删除文件

javascript - 使用 ramda.js assocPath 为多个键分配特定值?

javascript - Recharts - 水平对齐折线图和条形图

javascript - <Provider> 不支持在使​​用 componentWillMount 或 componentWillUnMount 时即时更改 `store`

reactjs - 使用 redux 表单中的 <select> 字段处理出生日期

javascript - 如何重写基本操作/ reducer 以使用 promise

Javascript FileReader 多个图像

reactjs - 更改 nginx 默认文件夹

reactjs - 从父级调用功能组件的子级方法

javascript - 在 Javascript 中从剪贴板读取文件