首页 > 解决方案 > 在 ReactJS 中验证来自后端的数据的正确位置是什么?

问题描述

假设我收到了这个 JSON:

"events": [
            {
              "description": "Some event",
              "details": "Issue found",
              "id": 0,
              "severity": "critical",
              "type": "blabla"
            },
]

我有一个Component使用该severity字段来定义它的 CSS 类(类似于className={e.serveity});

如果我收到一个severity不在预期中的内容(例如criticalwarning等),我想执行一些操作,例如渲染另一个组件或完全执行其他操作。

放置此验证码的正确位置是什么?应该是:

  1. Component自身内部;
  2. action承诺的负责人范围内;
  3. reducer;

标签: reactjsreduxreact-reduxfluxredux-thunk

解决方案


您应该在组件和组件内执行此操作,您可以在 react 提供的生命周期方法(如 componentWillMount、componentDidMount、componentWillReceiveProps 和渲染)中执行此操作。

请注意,最新的 React v16.3 已弃用 componentWillMount 和 componentWillReceiveProps。

所以你可以根据需要这样做

如果你想在渲染中做

render(){
     this.state.events.map(item => {
          if(item != “critical” && item != “warning”){
                 //do stuff here
          }
     });
     return(

     );
   }

有很多方法可以在组件中执行此类逻辑。所以对于你的问题,推荐的地方是组件。

Actions 用于调度 action,reducer 用于将数据设置为 Redux 状态。


推荐阅读