React 面试必知必会 Day13

1,526 阅读2分钟

这是我参与更文挑战的第19天,活动详情查看:更文挑战

大家好,我是 @洛竹,一个坚持写作的博主,感恩你的每一个点赞和评论。

本文首发于 洛竹的官方网站

本文翻译自 sudheerj/reactjs-interview-questions

本文同步于公众号洛竹早茶馆,转载请联系作者。

1. React 的常见文件夹结构是什么?

React 项目文件结构有两种常见做法。

  1. 按特性或路由分组:*

一种常见的项目结构方式是将 CSS、JS 和测试放在一起,按特性或路由分组。

common/
├─ Avatar.js
├─ Avatar.css
├─ APIUtils.js
└─ APIUtils.test.js
feed/
├─ index.js
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
└─ FeedAPI.js
profile/
├─ index.js
├─ Profile.js
├─ ProfileHeader.js
├─ ProfileHeader.css
└─ ProfileAPI.js
  1. 按文件类型分组:

另一种流行的项目结构方式是将类似的文件分组。

api/
├─ APIUtils.js
├─ APIUtils.test.js
├─ ProfileAPI.js
└─ UserAPI.js
components/
├─ Avatar.js
├─ Avatar.css
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
├─ Profile.js
├─ ProfileHeader.js
└─ ProfileHeader.css

2. 有哪些流行的动画包?

React Transition Group 和 React Motion 是 React 生态系统中流行的动画包。

3. 样式模块的好处是什么?

我们建议避免在组件中硬编码样式值。任何可能在不同的 UI 组件中使用的值都应该被提取到它们自己的模块中。

例如,这些样式可以被提取到一个单独的组件中。

export const colors = {
  white,
  black,
  blue,
};

export const space = [0, 8, 16, 32, 64];

然后在其他组件中单独导入。

import { space, colors } from './styles';

4. 有哪些流行的 React 专用 linter?

ESLint 是一个很流行的 JavaScript linter。有一些插件可以用来分析特定的代码风格。其中最常见的 React 插件是一个名为 eslint-plugin-react 的 npm 包。默认情况下,它将检查一些最佳实践,其规则是检查从迭代器中的键到一整套道具类型的东西。

另一个流行的插件是 eslint-plugin-jsx-a11y,它将帮助修复可访问性方面的常见问题。由于 JSX 提供了与常规 HTML 稍有不同的语法,例如 alt 文本和 tabindex 的问题将不会被常规插件发现。

5. 如何进行 AJAX 调用,应该在哪个组件的生命周期方法中进行 AJAX 调用?

你可以使用 AJAX 库,如 Axios、jQuery AJAX,以及浏览器内置的 fetch。你应该在 componentDidMount() 生命周期方法中获取数据。这样你就可以在获取数据时使用 setState() 来更新你的组件。

例如,从 API 获取的雇员名单并设置本地状态。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      employees: [],
      error: null,
    };
  }

  componentDidMount() {
    fetch('https://api.example.com/items')
      .then(res => res.json())
      .then(
        result => {
          this.setState({
            employees: result.employees,
          });
        },
        error => {
          this.setState({ error });
        },
      );
  }

  render() {
    const { error, employees } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else {
      return (
        <ul>
          {employees.map(employee => (
            <li key={employee.name}>
              {employee.name}-{employee.experience}
            </li>
          ))}
        </ul>
      );
    }
  }
}

6. 什么是渲染 props?

渲染 props是一种简单的技术,使用一个 props 在组件之间共享代码,其值是一个函数。下面的组件使用渲染 props,它返回一个 React 元素。

<DataProvider render={data => <h1>{`Hello ${data.target}`}</h1>} />

React Router 和 DownShift 等库正在使用这种模式。

这是 React 核心面试题最后一篇,后续会有 React Router、Redux 等继续更新,欢迎持续关注。