reactjs和微信分享_5个推荐的ReactJS技巧和最佳实践

reactjs和微信分享

React is something every front-end developer should have in their tool belt. Some new concepts need to be learned, and a few things we used to apply in traditional MVP apps need to be unlearned.That’s why I reached out to you to share knowledge and offer the best tips from some top React developers and engineers. Let’s get started!

React是每个前端开发人员都应该掌握的工具。 需要学习一些新概念,而我们过去在传统MVP应用程序中应用的一些知识则需要学习,这就是为什么我与您联系以分享知识并提供一些顶级React开发人员和工程师的最佳建议的原因。 让我们开始吧!

  1. How to deal with this Reference inside the promise?

    如何在Promise中处理 this Reference?

Image for post

使用React.js时,您可能会遇到如何从Promise内部访问this问题的问题。 例如,如下面的代码所示,问题之一可能是this是在promise内部解析为undefined(While working with React.js, chances are you’ve faced a problem with how to access this from inside the promise. For example, as exhibited in the code below, one of the problems could be this is resolving inside the promise as undefined:)

class Component extends React.Component { 
componentDidMount() {
axios.get(‘http://…’).then(function(data) {
this.setState( { name: data.blah } );
});
}
}

There’s more than one solution to determine this reference inside the promise. The earlier approach would be setting the self = this reference. While this would work, the recommended solution, which is more incline with ES6, would be to use an arrow function here:

在promise中确定引用的方法不止一种。 较早的方法是设置self = this参考。 虽然这可行,但建议的解决方案(更倾向于ES6)将在此处使用箭头功能:

class Component extends React.Component { 
componentDidMount() {
let component = this;
axios.get(‘http://…’).then(function(data) {
component.setState( { name: data.blah } );
});
}
}

The arrow syntax, as described above, is a much reliable way to allow a user of this to make reference to React.Component classes, as we can analyze below:

箭头语法,如上所述,是一个非常可靠的方法来允许用户this要参考React.Component类,我们可以分析如下:

class Component extends React.Component { 
componentDidMount() {
axios.get(‘http://…’).then(data => {
this.setState( { name: data.blah } );
});
}
}

Kindly note that instead of using function(data) { //body }, we used data => { //body }, and in this cases, this reference won’t get the promise instance back.

请注意,我们不是使用function(data) { //body } ,而是使用data => { //body } ,在这种情况下, this引用不会使promise实例返回。

2) How to use rc-chartjs or react-chartjs in React.js Application running Under webpack-dev-server?

2)如何 webpack-dev-server 下运行的React.js应用程序中 使用 rc-chartjs react-chartjs

Image for post
webpack-dev-server with hot reloading support. Individually, for this, I’m using a series of components that can b accessed in a webpack-dev-server开发应用程序。 为此,我个人使用了一系列可以在 React Transform Boilerplate. React Transform Boilerplate中访问的组件。

After you’ve hot reloading working rightly, you may end up facing issues with some JavaScript references inside third-party React.js components, like react-chartjs component highlighted above in the title. In this particular case, most probably react-chartjs, and its fork rc-chartjs, have a similar kind of problem: they can’t reach a reference to a window object when scripts is bundled by webpack and served by webpack-dev-server.

在正确进行热加载后,您可能最终会遇到第三方React.js组件(例如标题chartjs突出显示的react-chartjsjs组件)中的一些JavaScript引用的问题。 在这种情况下,很可能react-chartjs及其fork rc-chartjs都有类似的问题:当脚本由webpack捆绑并由webpack-dev-server提供服务时,它们无法到达对window对象的引用。

To fix this, I used the import-loader provided by Webpack. Look at the …. Configuration example below:

为了解决这个问题,我使用了Webpack提供的import-loader。 看着那(这 …。 下面的配置示例:

module: {
loaders: [
{test: require.resolve(‘chart.js’), loader: ‘imports?this=>window’},
]
}

As you can see, we’re injecting this reference to a window object straight into chart.js library.

正如你所看到的,我们注入this参照window对象直冲chart.js库。

3)如何在React.js应用程序中使用依赖注入? (3) How to use dependency injection in React.js application?)

Image for post

As JavaScript developers, dependency injection is one of the finest software design practices that we have at our disposal. By using dependency, we can avoid multiple duplicated code in the application, largely regarding services initialization and configuration.In the example below, I made use of a dependency injection library called Jimple to handle the injection of my service layer code into the components. But first, I need to ensure the Jimple container is injected rightly on each React.js component.

作为JavaScript开发人员,依赖注入是我们可以使用的最好的软件设计实践之一。 通过使用依赖关系,我们可以避免应用程序中出现重复的代码,主要是关于服务的初始化和配置。在下面的示例中,我使用了一个名为Jimple的依赖关系注入库来处理将服务层代码注入组件的过程。 但是首先,我需要确保在每个React.js组件上正确注入了Jimple容器。

Let’s have a look first on container description:

让我们先来看一下容器描述:

import Jimple from ‘jimple’;import { UsersService } from ‘./services/UsersService’;export let container = new Jimple();container.set(‘API_URL’, function © {
return ‘http://localhost:8080/api';
});container.set(‘API_VERSION’, function © {
return ‘1.0.0’;
});container.set(‘USERS_SERVICE’, function © {
return new UsersService(c.get(‘API_URL’), c.get(‘API_VERSION’));
});

Next, on the Router component we need to inject the container on each Component rendered by its routes. For this, we defined a function named as createElement which allows us to advance the container to component as a property:

接下来,在Router组件上,我们需要将容器注入到其路由所呈现的每个Component 。 为此,我们定义了一个名为createElement的函数,该函数使我们可以将容器作为属性推进到组件:

import { Router, IndexRedirect, Route, History } from ‘react-router’;import { container } from ‘./container’;class MoneyApp extends React.Component {
render() {
return <div>{this.props.children}</div>
}
}// Pass container as prop to children components
function createElement(Component, props) {
return <Component container={container} {…props}/>
}render((
<Router history={history} createElement={createElement}>
<Route path=”/” component={MyApp}>
<Route path=”/login” component={Login} />
<Route path=”/dashboard” component={Dashboard}>
<Route path=”/dashboard/overview” component={Overview} />
</Route>
<IndexRedirect to=”dashboard” />
</Route>
</Router>),
document.getElementById(‘app’));

In the end, we can retrieve the dependencies as we will do in the example below:

最后,我们可以像下面的示例一样检索依赖项:

class Overview extends React.Component {
constructor() {
super();
this.state = { pending: [], lastMonths: [] }
}
componentDidMount() {
let service = this.props.container.get(‘SERVICE’);
service.yourMethod();
}
render() {
return <div><span>Some content</span></div>
}
}

4)避免在组件中使用className和Style (4) Avoid className and Style in your components)

If you want your application to have to consistent look and feel, you don’t want to pass around classNames and styles in an ad-hoc manner. Keeping the possibility to pass any style or className to a component means that:

如果你希望你的应用程序具有一致的外观和感觉,你不想绕过classNames和样式在ad-hoc方式。 保持将任何样式或className传递给组件的可能性意味着:

  • You’ve to consider what style it requires to make it look the way you want.

    您必须考虑需要哪种样式才能使其看起来像您想要的样子。
  • You’ve to understand the default set of styles, in order to know the styles from the beginning point.

    您必须了解默认样式集,才能从一开始就了解样式。
  • You can pass any kind of styles that don’t make sense and may interrupt your UI.

    您可以传递任何没有意义的样式,并可能会中断您的UI。

Let’s see what I’m talking about with some examples.

让我们来看一些例子。

Let’s render a ‘primary’ button to start.

让我们渲染一个“主要”按钮开始。

<button type=”button” className=”btn btn-primary”>Press me!</button>

<button type=”button” className=”btn btn-primary”>Press me!</button>

In the above example, we’ve to know that we need to pass the classes btn-primary. Also, we could pass any other className that would not make wisdom, like make-this-look-like-a-pig.

在上面的示例中,我们必须知道需要传递btn-primary类。 同样,我们可以传递任何其他不会产生智慧的className ,例如make-this-look-like-a-pig

Instead, consider the following code snippet:

相反,请考虑以下代码片段:

<Button primary>Press me!</Button>

<Button primary>Press me!</Button>

In the code pattern above, we use a custom Button component that internally may use the initial approach but just exposes a primary Boolean property like this:

在上面的代码模式中,我们使用了一个自定义的Button组件,该组件在内部可以使用初始方法,但是只公开了一个primary Boolean属性,如下所示:

class Button extends React.Component {
render() {
// Using https://github.com/JedWatson/classnames
var className = classNames(‘btn’, this.props.primary && ‘btn-primary’);
return <button type=”button” className={className} onClick={this.props.onClick}>
{this.props.children}
</button>;
}
}

Let’s consider another example. We want to render the principal content on the left, and the sidebar on the right:

让我们考虑另一个例子。 我们要在左侧显示主要内容,在右侧显示侧边栏:

<div style={{float: ‘left’, width: ‘80%’}}>
Main content
</div>
<div style={{float: ‘left’, width: ‘20%’}}>
Sidebar content
</div>

What if we want to use flexbox? We need to come here and modify the styles we’re passing to the div. Moreover, we can pass any other style that we want, including styles that do not make any sense or that we don’t intend someone to use.

如果我们想使用flexbox怎么办? 我们需要来到这里并修改传递给div的样式。 此外,我们可以传递我们想要的任何其他样式,包括没有任何意义或不打算让他人使用的样式。

Now instead, take a look at the following code:

现在,改为看下面的代码:

<Main>
Main content
</Main>
<Sidebar>
Sidebar content
</Sidebar>

We encased that piece of the layout into different components, which hide that style implementation detail away from us, and we simply use them. This specific piece of code doesn’t even care if the sidebar is on the right or on the left.

我们将布局的一部分封装到不同的组件中,这些组件将样式实现的细节隐藏在我们身边,而我们只是使用它们。 这段特定的代码甚至不在乎侧边栏是在右侧还是在左侧。

One more example, exhibiting a successful notification:

再举一个成功的通知示例:

<div className=”notification notification-success”>
A good notification
</div>

Same issue as the first example. We need to know that those classes need to be implemented.

与第一个示例相同的问题。 我们需要知道那些类需要实现。

<Notification type=”success”>
A good notification
</Notification>

Using a custom notification component that takes a type, and which can be validated via React.PropTypes to just be any value of a predefined set makes the user of this component not need to rethink of any class convention.

使用带有类型的自定义通知组件,该组件可以通过React.PropTypes进行验证, 使其只是预定义集合的任何值,因此该组件的用户无需重新考虑任何类约定。

One final example. Let’s consider how we could simplify layouting a form by defining a Layout Component that postulates the width of its children.

最后一个例子。 让我们考虑一下如何通过定义一个假定其子级宽度的Layout组件来简化表单的Layout

Here we first layout three inputs in a similar row, where the first two have equal size, and the third one is half of the size of the others, with the row taking the whole width of the container. Then we render another row with a button taking full width.

在这里,我们首先将三个输入布置在相似的行中,其中前两个的大小相等,而第三个是其他大小的一半,该行占据容器的整个宽度。 然后,我们渲染另一个带有全角按钮的行。

<Layout sizes={[1, 1, 0.5]}>
<Input placeholder=”First Name” />
<Input placeholder=”Last Name” />
<Input placeholder=”Age” />
</Layout>
<Layout>
<Button>Submit</Button>
</Layout>

Please consider how avoiding styles and classNames forces you to distinguish styling concerns like how it looks vs. how it lays out, which suggests you’ll have different components to enforce each. In the last example, the Input and Buttons have no clue how they will lay out. That’s the job for a parent component.

请考虑避免风格,以及如何classNames的力量,你分辨造型像它的外观与它是如何勾画出,这表明你有不同的组件来执行各担忧。 在最后一个示例中, InputButtons不知道它们的布局方式。 这就是父组件的工作。

Think about components’ properties as their API. Exposing classNames or styles is like exposing an ‘options’ object which can have hundreds of routes. Do you really think that for your own components? Do you actually want to think about every possible option when you use them?

将组件的属性视为其API。 暴露classNames或样式就像是一个暴露的“选项”对象,可以有上百路线。 您是否真的认为适合您自己的组件? 使用它们时,您是否真的想考虑所有可能的选择?

It will be good to leave styles and className to be used in leaf-most components and create a set of components that will build look and feel, and another set that will define layout.

最好保留样式和className以便在最叶的组件中使用,并创建一组将构建外观的组件,以及另一组将定义布局的组件。

When you execute this, it will become much simpler to generate new components, pages, and views of your app, since you’ll only need to arrange your set of appearance and layout of components and pass them the right props without even anticipating about CSS or styles.

当您执行此操作时,生成应用程序的新组件,页面和视图将变得更加简单,因为您只需要安排组件的外观和布局集,并通过正确的道具,甚至不必担心CSS或样式。

If you want to tweak the styles or modify the look and feel of your application as an added benefit, you will just need to change the library components. Also, if you keep the identical API for them, the components that use them will remain untouched.

如果您想调整样式或修改应用程序的外观作为附加好处,则只需要更改库组件即可。 另外,如果为它们保留相同的API,则使用它们的组件将保持不变。

5.创建只做一件事情的微小组件 (5. Create tiny components that just do One Thing)

Generate small components that halt particular parts of your page or add specific new behavior to your UI. You’ll be able to consider each piece individually, and you will even be able to benefit from performance optimization like shouldComponentUpdate in a more granular manner, or other lifecycle components.Moreover, they will become more reusable across your application. Not to indicate to the React community, if they’re generic enough.

生成小组件,以停止页面的特定部分或向UI添加特定的新行为。 您将能够分别考虑每个组件,甚至还可以从性能优化中受益,例如以更精细的方式使用shouldComponentUpdate或其他生命周期组件。此外,它们将在您的应用程序中变得更加可重用。 如果它们足够通用,不要向React社区指出。

A few hints to know if you separate your component:

一些提示可帮助您了解是否要分离组件:

  • Keep your render function short and simple. You can split the render function into various functions in a similar component, but if it makes sense, try splitting those render chunks into separate components.

    保持渲染功能简短明了。 您可以在相似的组件中将render函数拆分为各种函数,但是如果有意义,请尝试将这些渲染块拆分为单独的组件。
  • Are you working with application state logic and also a presentation in the same component? Attempt to separate it into a component that just handles the state and one or several components that handle the presentation, where the state is passed as a property to the child components.

    您是否正在使用应用程序状态逻辑以及同一组件中的演示? 尝试将其分为一个仅处理状态的组件和一个或多个处理表示的组件,其中状态作为属性传递给子组件。
  • Do you have some elements in your render method that require to be updated much more frequently than others? Extract that chunk into a separate component, and try to localize the state updates inside (if it makes sense), or use shouldComponentUpdate in the other components to prevent any unnecessary re-renders.

    您的render方法中是否有一些元素需要比其他元素更频繁地更新? 将该块提取到一个单独的组件中,并尝试在其内部本地化状态更新(如果有意义),或者在其他组件中使用shouldComponentUpdate ,以防止任何不必要的重新渲染。

  • Do you have a form with various sections and fields but you really don’t care about all the intermediate state, Extract that form into its own component (or even varying sections of the form into their own components) that accept the primary values as properties, and have an onSubmit callback property that’s called with end values of the form, making the parent not need to re-render every time an intermediate change in the form occurs. Internally in those section components, either uses uncontrolled components or implement the component internal state.

    您是否有一个包含不同部分和字段的表单,但是您真的不在乎所有中间状态,将表单提取到其自己的组件中(甚至将表单的不同部分提取到自己的组件中),这些表单接受主值作为属性,并具有一个onSubmit回调属性,该属性以表单的结束值调用,从而使父级不需要每次在表单中发生中间更改时都重新呈现。 在这些部分的组件内部,要么使用不受控制的组件,要么实现组件内部状态。

  • Are you doing a lot of styling for layouting a set of components? Exact that into layout components that have configurable yet predefined layouts and place your components as children of them.

    您是否正在为设置一组组件做很多样式设计? 将其精确地放入具有可配置但预定义布局的布局组件中,然后将组件作为它们的子组件放置。
  • Are you adding behavior to some component through the state like collapsing, expanding, hovering, or making it pop over? Move that behavior into separate components that take a single child which is a function to render, and sets the state via patterns to that function, like:

    您是否正在通过折叠,展开,悬停或弹出状态来向某些组件添加行为? 将该行为移到带有一个要渲染的功能的单个子元素的单独组件中,并通过模式将该功能设置为状态,例如:
<Hoverable>
{hovered => <div>{hovered ? “I’m hovered!” : “I’m not hovered”}</div>}
</Hoverable>

结论 (Conclusion)

There are precisely several reasons to split your current component into more. Remember, components in React are quite like functions. You can split a function into many. Also, you can compose or combine them in any way you want, and still get the same result.

将您的当前组件拆分成更多的原因有很多。 记住,React中的组件非常像函数。 您可以将一个功能拆分为多个。 此外,您可以按任意方式组合或组合它们,而仍然得到相同的结果。

For coronavirus updates, you can visit CNBC Live Stream.

有关冠状病毒的更新,您可以访问CNBC Live Stream

使用Bit共享和管理可重复使用的React组件 (Share & Manage Reusable React Components with Bit)

Use Bit (Github) to share, document, and manage reusable components from different projects. It’s a great way to increase code reuse, speed up development, and build apps that scale.

使用Bit ( Github )共享,记录和管理来自不同项目的可重用组件。 这是增加代码重用,加速开发并构建可扩展应用程序的好方法。

Image for post
Example: React components shared on Bit
示例:在Bit上共享React组件

翻译自: https://blog.bitsrc.io/5-recommended-reactjs-tips-and-best-practices-9a7e2f6526a4

reactjs和微信分享

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值