简体   繁体   English

危险地反应SetInnerHTML错误导致Redux中的承诺被拒绝

[英]React dangerouslySetInnerHTML error causing promise rejection in Redux

I have a React component set up to display content from a CMS, where I use dangerouslySetInnerHTML . 我已经设置了一个React组件来显示来自CMS的内容,在其中我使用了dangerouslySetInnerHTML I have a standard fetch, request, receive pattern set up with a thunk to handle the async action. 我有一个标准的fetch,request,receive模式,设置了一个thunk来处理异步操作。

The action creator looks like this: 动作创建者如下所示:

export const fetchPage = (slug) => {
  return (dispatch) => {
    dispatch(requestPage());
    return fetch(`${config.api}/pages/?slug=${slug}`)
      .then((response) => {
        const status = response.status;
        switch (status) {
          case 200:
            return response.json();
          case 401:
            return Promise.reject(status);
          default:
            return Promise.reject(status);
        }
      })
      .then(json =>
        dispatch(receivePage({
          slug,
          json,
        }))
      ).catch(err =>
        dispatch(receivePageError(err)));
  };
};

When I first created the React component, I forgot to pass to dangerouslySetInnerHTML the object in format { __html: content } and just passed it content , giving me the invariant violation. 当我第一次创建React组件时,我忘记了将{ __html: content }格式的对象传递给dangerouslySetInnerHTML { __html: content }而只是将其传递给content ,这给了我不变的侵犯。 What confuses me is that this error bubbled up into the redux async flow and caused a dispatch of receivePageError. 令我困惑的是,该错误冒泡到redux异步流中,并导致了receivePageError的调度。 Why did this error show up here, rather than in the React component itself? 为什么这个错误出现在这里,而不是出现在React组件本身中?

The error has been caught by the Promise's catch. 该错误已由Promise的陷阱捕获。 The code example will console log the exception. 该代码示例将控制台记录异常。

 const callAnError = () => { throw Error('Error'); } const callAnErrorParent = () => { callAnError(); } const callAnErrorGrandparent = () => { callAnErrorParent(); }; Promise.resolve().then(() => { callAnErrorGrandparent(); }).catch((error) => { console.log(error); }); 

https://jsfiddle.net/nfyeu5co/1/ https://jsfiddle.net/nfyeu5co/1/

This is great resource for understanding promises 这是理解诺言的重要资源

https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch3.md https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch3.md

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM