【问题标题】:Why am I not able to render my header?为什么我无法呈现我的标题?
【发布时间】:2018-06-04 09:34:59
【问题描述】:

我试图让Tech Stack 出现在iOS 模拟器的顶部。相反,我的两个 .js 文件都出现了一个奇怪的错误,尽管它们在语法上看起来是正确的。

错误提示:unexpected block statement surrounding arrow body arrow-body-style 在两个 .js 文件上。

我偶然发现了这个网站https://eslint.org/docs/rules/arrow-body-style 以获取更多信息并彻底搜索解决方案,但找不到任何东西。

(错误的位置在两个.js文件中都有注释)

我该如何解决这个问题?

模拟器出错:

这里是app.js:

import React from 'react';
import { View } from 'react-native';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from './reducers';
import { Header } from './components/common';

const App = () => { // error is on this line
  return (
    <Provider store={createStore(reducers)}>
      <View>
        <Header headerText="Tech Stack" />
      </View>
    </Provider>
  );
};

export default App;

这里是CardSection.js

import React from 'react';
import { View } from 'react-native';

const CardSection = (props) => { // error is on this line
  return (
    <View style={styles.containerStyle}>
      {props.children}
    </View>
  );
};

const styles = {
  containerStyle: {
    borderBottomWidth: 1,
    padding: 5,
    backgroundColor: '#fff',
    justifyContent: 'flex-start',
    flexDirection: 'row',
    borderColor: '#ddd',
    position: 'relative'
  }
};

export { CardSection };

【问题讨论】:

    标签: javascript reactjs react-native jsx eslint


    【解决方案1】:

    您的项目似乎启用了eslint。要摆脱这个 eslint 错误,您应该将您的 App 组件包装到括号中,如下所示

    const App = () => (
      <Provider store={createStore(reducers)}>
        <View>
          <Header headerText="Tech Stack" />
        </View>
      </Provider>
    )
    

    这种情况下不需要大括号。

    希望它会有所帮助。

    【讨论】:

      【解决方案2】:

      表示不需要块体,使用简洁的体,像这样:

      const App = () => (    // not {, use (
          <Provider store={createStore(reducers)}>
              <View>
                  <Header headerText="Tech Stack" />
              </View>
          </Provider>
      );
      

      arrow function [MDN Doc]有两种使用方式:

      1- 块体:当使用{} 并且在体内部需要显式返回时,当你有一些 js 逻辑比如做一些计算、创建函数/变量时它是有用的。 p>

      例子:

      const Hello = () => {
          const name = 'ABC';
          // other logic
          return (<div> Hello {name} </div>);
      }
      

      2- 简洁的正文:当你想直接退货时,使用(),不需要return。

      【讨论】:

      • 啊好吧,我明白了!但每当我对CardSection.js 进行此更改时,它不会让我这样做。
      • 是的,出于某种原因,同样的错误。但它适用于App.js 没有问题。
      • 也许是因为在 CardSection 中,我要返回一些东西。在 App.js 中,没有返回任何内容。
      • 这样写:const CardSection = props =&gt; ( &lt;View style={styles.containerStyle}&gt; {props.children} &lt;/View&gt; );
      • 是的,出于某种原因。我忘了最初提到这个红色错误。 (查看我的原帖)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      相关资源
      最近更新 更多