您的位置:首页 > Web前端 > React

react中使用构建缓存_如何使用React构建Chatbot

2020-08-21 02:55 1271 查看

react中使用构建缓存

My philosophy is simple. To become good at something, you need to do it a lot.

我的哲学很简单。 要变得擅长某件事,您需要做很多事情。

It's not enough to do it once. You need to do it again, and again and again. It will never end. I used the same philosophy to get good at programming.

仅做一次是不够的。 您需要一次又一次地这样做。 它永远不会结束。 我使用相同的哲学来擅长编程。

One thing I've noticed on this journey is that it's a lot more fun to build things that are interesting, and that look good. Things you can show you friends and be proud of. Something that makes you excited to get started when you sit down in front of your keyboard.

我在此过程中注意到的一件事是,构建有趣且看起来不错的东西会更加有趣。 您可以向朋友展示并为之骄傲的事物。 当您坐在键盘前时,会让您兴奋的开始。

That's why I built a chatbot.

这就是为什么我建立了一个聊天机器人。

Which morphed into a npm package.

变成了npm包。

So let's build one together. If you want to take on this challenge on your own, you can go directly to the documentation (which is actually a chatbot). Or, if you are a visual learner, I created a tutorial on YouTube.

因此,让我们一起构建一个。 如果您想独自承担这个挑战,则可以直接转到文档(实际上是一个聊天机器人) 。 或者,如果您是视觉学习者,那么我在YouTube上创建了一个教程。

Otherwise, let's go. I'm going to assume that you have Node installed, and access to the npx command. If not, go get it here.

否则,我们走吧。 我将假定您已安装Node,并可以访问npx命令。 如果没有, 请在这里获取。

最初设定 (Initial setup)

// Run these commands from your command line
npx create-react-app chatbot
cd chatbot
yarn add react-chatbot-kit
yarn start

This should install the npm package and open the development server at localhost:3000.

这应该安装npm软件包并在localhost:3000处打开开发服务器。

Next head over to

App.js
and make these changes:

接下来转到

App.js
并进行以下更改:

import Chatbot from 'react-chatbot-kit'

function App() {
return (
<div className="App">
<header className="App-header">
<Chatbot />
</header>
</div>
);
}

Great job. We're getting there. You should see this in your development server now:

很好。 我们到了。 您现在应该在开发服务器中看到以下内容:

The chatbot takes three props that must be included for it to work. First, it needs a config which must include an

initialMessages
property with chatbot message objects.

聊天机器人需要包含三个道具才能正常工作。 首先,它需要一个配置,该配置必须包含带有chatbot消息对象的

initialMessages
属性。

Secondly, it needs a

MessageParser
class that must implement a parse method.

其次,它需要一个必须实现解析方法的

MessageParser
类。

Thirdly, it needs an

ActionProvider
class which will implement actions that we want to take based on parsing the message.

第三,它需要一个

ActionProvider
类,该类将基于解析消息来实现我们要执行的操作。

We'll go deeper into this later. For now, go here to get the boilerplate code to get started.

我们稍后将对此进行更深入的研究。 现在, 请转到此处获取样板代码以开始使用。

  • Put the

    MessageParser
    code in a file called
    MessageParser.js

    MessageParser
    代码放入一个名为
    MessageParser.js
    的文件中

  • Put the

    ActionProvider
    code in a file called
    ActionProvider.js

    ActionProvider
    代码放入名为
    ActionProvider.js
    的文件中

  • Put the config code in a file called

    config.js

    将配置代码放入名为

    config.js
    的文件中

When that's done, go back to your

App.js
file and add this code:

完成后,返回您的

App.js
文件并添加以下代码:

import React from 'react';
import Chatbot from 'react-chatbot-kit'
import './App.css';

import ActionProvider from './ActionProvider';
import MessageParser from './MessageParser';
import config from './config';

function App() {
return (
<div className="App">
<header className="App-header">
<Chatbot config={config} actionProvider={ActionProvider} 	    messageParser={MessageParser} />
</header>
</div>
);
}

You should now see this on localhost:3000:

您现在应该在localhost:3000上看到以下内容:

Sweet. Now we have the chatbot rendered to the screen and we can write in the input field and submit it to send a message to the chat. But when we try that, nothing happens.

甜。 现在,我们将聊天机器人呈现到屏幕上,我们可以在输入字段中进行编写并提交,以向聊天室发送消息。 但是,当我们尝试这样做时,什么也没有发生。

了解聊天机器人的工作原理 (Understanding how the chatbot works)

Here we need to take a pit stop and take a look at how the

MessageParser
and
ActionProvider
interacts to make our bot take action.

在这里,我们需要进站,看看

MessageParser
ActionProvider
如何交互以使我们的机器人采取行动。

When the bot is initialized, the

initialMessages
property from the config is put into the chatbot's internal state in a property called
messages
, which is used to render messages to the screen.

初始化漫游器后,配置中的

initialMessages
属性将进入聊天机器人的内部状态,该属性称为
messages
,该属性用于将消息呈现到屏幕。

Moreover, when we write and push the submit button in the chat field, our

MessageParser
(which we passed as props to the chatbot) is calling its
parse
method. This is why this method must be implemented.

此外,当我们在聊天字段中编写并按下“提交”按钮时,我们的

MessageParser
(作为道具传递给聊天机器人)正在调用其
parse
方法。 这就是为什么必须实现此方法的原因。

Let's take a closer look at the

MessageParser
starter code:

让我们仔细看看

MessageParser
入门代码:

class MessageParser {
constructor(actionProvider) {
this.actionProvider = actionProvider;
}

parse(message) {
... parse logic
}
}

If we look closely, this method is constructed with an

actionProvider
. This is the same
ActionProvider
class that we pass as props to the chatbot. This means that we control two things - how the message is parsed, and what action to take based on said parsing.

如果仔细观察,此方法是使用

actionProvider
构造的。 这是我们作为道具传递给聊天机器人的同一个
ActionProvider
类。 这意味着我们控制着两件事-消息的解析方式以及基于该解析采取的操作。

Let's use this information to create a simple chatbot response. First alter the

MessageParser
like this:

让我们使用此信息来创建一个简单的聊天机器人响应。 首先像这样更改

MessageParser

class MessageParser {
constructor(actionProvider) {
this.actionProvider = actionProvider;
}

parse(message) {
const lowerCaseMessage = message.toLowerCase()

if (lowerCaseMessage.includes("hello")) {
this.actionProvider.greet()
}
}
}

export default MessageParser

Now our

MessageParser
is receiving the user message, checking if it includes the word "hello". If it does, it calls the
greet
method on the
actionProvider
.

现在,我们的

MessageParser
正在接收用户消息,检查它是否包含单词“ hello”。 如果是这样,它将在
actionProvider
上调用
greet
方法。

Right now, this would crash, because we haven't implemented the

greet
method. Let's do that next. Head over to
ActionProvider.js
:

现在,这将崩溃,因为我们尚未实现

greet
方法。 让我们接下来做。 转到
ActionProvider.js

class ActionProvider {
constructor(createChatBotMessage, setStateFunc) {
this.createChatBotMessage = createChatBotMessage;
this.setState = setStateFunc;
}

greet() {
const greetingMessage = this.createChatBotMessage("Hi, friend.")
this.updateChatbotState(greetingMessage)
}

updateChatbotState(message) {

// NOTE: This function is set in the constructor, and is passed in      // from the top level Chatbot component. The setState function here     // actually manipulates the top level state of the Chatbot, so it's     // important that we make sure that we preserve the previous state.

this.setState(prevState => ({
...prevState, messages: [...prevState.messages, message]
}))
}
}

export default ActionProvider

Nice. Now if we type in "hello" into the chat field, we get this back:

真好 现在,如果我们在聊天字段中输入“ hello”,我们将得到以下信息:

Fantastic. Now that we can control parsing the message and responding with an action, let's try to make something more complicated. Let's try to make a bot that provides you with learning resources for the programming language you ask for.

太棒了 现在我们可以控制解析消息并以操作进行响应,让我们尝试使事情变得更复杂。 让我们尝试创建一个机器人,为您提供所需编程语言的学习资源。

创建一个学习机器人 (Creating a learning bot)

First, let's go back to our

config.js
file and make some slight changes:

首先,让我们回到

config.js
文件并进行一些细微更改:

import { createChatBotMessage } from 'react-chatbot-kit';

const config = {
botName: "LearningBot",
initialMessages: [createChatBotMessage("Hi, I'm here to help. What do you want to learn?")],
customStyles: {
botMessageBox: {
backgroundColor: "#376B7E",
},
chatButton: {
backgroundColor: "#376B7E",
},
},
}

export default config

OK, so we've added some properties here and changed our initial message. Most notably we have given the bot a name and changed the color of the

messagebox
and
chatbutton
components.

好的,因此我们在此处添加了一些属性,并更改了初始消息。 最值得注意的是,我们给机器人赋予了名称,并更改了

messagebox
chatbutton
组件的颜色。

Alright. Now we're getting to the good part.

好的。 现在,我们进入了很好的阶段。

Not only can we parse messages and the respond to the user with a chatbot message, we can define custom React components that we want to render with the message. These components can be anything we want – they are just plain old React components.

我们不仅可以解析消息,还可以使用聊天机器人消息来响应用户,还可以定义要与消息一起呈现的自定义React组件。 这些组件可以是我们想要的任何东西,它们只是普通的旧React组件。

Let's try it out by creating an options component that will guide the user to possible options.

让我们通过创建一个选项组件来尝试一下,该组件将指导用户使用可能的选项。

First, we define the learning options component:

首先,我们定义学习选项组件:

// in src/components/LearningOptions/LearningOptions.jsx

import React from "react";

import "./LearningOptions.css";

const LearningOptions = (props) => {
const options = [
{ text: "Javascript", handler: () => {}, id: 1 },
{ text: "Data visualization", handler: () => {}, id: 2 },
{ text: "APIs", handler: () => {}, id: 3 },
{ text: "Security", handler: () => {}, id: 4 },
{ text: "Interview prep", handler: () => {}, id: 5 },
];

const optionsMarkup = options.map((option) => (
<button
className="learning-option-button"
key={option.id}
onClick={option.handler}
>
{option.text}
</button>
));

return <div className="learning-options-container">{optionsMarkup}</div>;
};

export default LearningOptions;

// in src/components/LearningOptions/LearningOptions.css

.learning-options-container {
display: flex;
align-items: flex-start;
flex-wrap: wrap;
}

.learning-option-button {
padding: 0.5rem;
border-radius: 25px;
background: transparent;
border: 1px solid green;
margin: 3px;
}

Now that we have our component, we need to register it with our chatbot. Head over to

config.js
and add the following:

现在我们有了组件,我们需要在聊天机器人中注册它。 转到

config.js
并添加以下内容:

import React from "react";
import { createChatBotMessage } from "react-chatbot-kit";

import LearningOptions from "./components/LearningOptions/LearningOptions";

const config = {
initialMessages: [
createChatBotMessage("Hi, I'm here to help. What do you want to 		learn?", {
widget: "learningOptions",
}),
],
...,
widgets: [
{
widgetName: "learningOptions",
widgetFunc: (props) => <LearningOptions {...props} />,
},
],
}

了解小部件 (Understanding widgets)

Alright. Let's take a breather and explore what we've done.

好的。 让我们喘口气,探索我们所做的事情。

  1. We created the

    LearningOptions
    component.

    我们创建了

    LearningOptions
    组件。

  2. We registered the component under

    widgets
    in our config.

    我们在配置中的

    widgets
    部件下注册了该组件。

  3. We gave the

    createChatbotMessage
    function an options object specifying which widget to render with this message.

    我们为

    createChatbotMessage
    函数提供了一个options对象,该对象指定了要使用此消息呈现的窗口小部件。

The result:

结果:

Fantastic, but why did we need to register our component in the config as a widget function?

太棒了,但是为什么我们需要在配置中将组件注册为小部件函数?

By giving it a function, we control when we perform the invocation. This allows us room to decorate the widget with important properties inside the chatbot.

通过给它一个函数,我们控制何时执行调用。 这使我们有空间用聊天机器人内部的重要属性来装饰小部件。

The widget that we define will receive a number of properties from the chatbot (some of which can be controlled by config properties):

我们定义的小部件将从聊天机器人接收许多属性(其中一些可以由config属性控制):

  1. actionProvider
    - we give the
    actionProvider
    to the widget in order to execute actions if we need to.

    actionProvider
    我们将
    actionProvider
    赋予窗口小部件,以便在需要时执行操作。

  2. setState
    - we give the top level chatbot
    setState
    function to the widget in case we need to manipulate state.

    setState
    在需要操纵状态的情况下,我们将顶级聊天机器人
    setState
    函数提供给小部件。

  3. scrollIntoView
    - utility function to scroll to the bottom of the chat window, should we need to adjust the view.

    scrollIntoView
    实用工具功能,可在需要调整视图时滚动到聊天窗口的底部。

  4. props
    - if we define any props in the widget config, those will be passed to the widget under the property name
    configProps
    .

    props
    如果我们在小部件config中定义了任何props,它们将以属性名
    configProps
    传递到小部件。

  5. state
    - if we define custom state in the config, we can map it to the widget by using the
    mapStateToProps
    property

    state
    -如果我们在配置定义自定义的状态,我们可以把它通过映射到小部件
    mapStateToProps
    财产

If you recall, we defined some options in the

LearningOptions
component:

回想一下,我们在

LearningOptions
组件中定义了一些选项:

const options = [
{ text: "Javascript", handler: () => {}, id: 1 },
{ text: "Data visualization", handler: () => {}, id: 2 },
{ text: "APIs", handler: () => {}, id: 3 },
{ text: "Security", handler: () => {}, id: 4 },
{ text: "Interview prep", handler: () => {}, id: 5 },
];

Currently these have an empty handler. What we want to do now is to replace this handler by a call to the

actionProvider
.

当前这些具有空处理程序。 我们现在要做的是通过调用

actionProvider
来替换此处理程序。

So what do we want to have happen when we execute these functions? Ideally, we'd have some sort of chatbot message, and an accompanying widget that displays a list of links to helpful resources for each topic. So let's see how we can implement that.

那么,当我们执行这些功能时,我们希望发生什么? 理想情况下,我们将有某种聊天机器人消息,以及一个附带的小部件,该小部件显示指向每个主题的有用资源的链接列表。 因此,让我们看看如何实现它。

First, we need to create the link list component:

首先,我们需要创建链接列表组件:

// in src/components/LinkList/LinkList.jsx

import React from "react";

import "./LinkList.css";

const LinkList = (props) => {
const linkMarkup = props.options.map((link) => (
<li key={link.id} className="link-list-item">
<a
href={link.url}
target="_blank"
rel="noopener noreferrer"
className="link-list-item-url"
>
{link.text}
</a>
</li>
));

return <ul className="link-list">{linkMarkup}</ul>;
};

export default LinkList;

// in src/components/LinkList/LinkList.css

.link-list {
padding: 0;
}

.link-list-item {
text-align: left;
font-size: 0.9rem;
}

.link-list-item-url {
text-decoration: none;
margin: 6px;
display: block;
color: #1d1d1d;
background-color: #f1f1f1;
padding: 8px;
border-radius: 3px;
box-shadow: 2px 2px 4px rgba(150, 149, 149, 0.4);
}

Great. We now have a component that can display a list of links. Now we need to register it in in the widget section of the config:

大。 现在,我们有一个可以显示链接列表的组件。 现在我们需要在配置的小部件部分中注册它:

import React from "react";
import { createChatBotMessage } from "react-chatbot-kit";

import LearningOptions from "./components/LearningOptions/LearningOptions";
import LinkList from "./components/LinkList/LinkList";

const config = {
...
widgets: [
{
widgetName: "learningOptions",
widgetFunc: (props) => <LearningOptions {...props} />,
},
{
widgetName: "javascriptLinks",
widgetFunc: (props) => <LinkList {...props} />,
},
],
};

export default config;

So far so good, but we want to dynamically pass in props to this component so that we can reuse it for the other options as well. This means that we need to add another property to the widget object in the config:

到目前为止,一切都很好,但是我们希望将props动态传递给该组件,以便我们也可以将其重用于其他选项。 这意味着我们需要在配置中的小部件对象中添加另一个属性:

import React from "react";
import { createChatBotMessage } from "react-chatbot-kit";

import LearningOptions from "./components/LearningOptions/LearningOptions";
import LinkList from "./components/LinkList/LinkList";

const config = {
...,
widgets: [
...,
{
widgetName: "javascriptLinks",
widgetFunc: (props) => <LinkList {...props} />,
props: {
options: [
{
text: "Introduction to JS",
url:
"https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/",
id: 1,
},
{
text: "Mozilla JS Guide",
url:
"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide",
id: 2,
},
{
text: "Frontend Masters",
url: "https://frontendmasters.com",
id: 3,
},
],
},
},
],
};

export default config;

Now these props will be passed to the

LinkList
component as props.

现在,这些道具将作为道具传递到

LinkList
组件。

Now we need to do two more things.

现在我们需要做两件事。

  1. We need to add a method to the

    actionProvider

    我们需要向

    actionProvider
    添加一个方法

class ActionProvider {
constructor(createChatBotMessage, setStateFunc) {
this.createChatBotMessage = createChatBotMessage;
this.setState = setStateFunc;
}

handleJavascriptList = () => {
const message = this.createChatBotMessage(
"Fantastic, I've got the following resources for you on Javascript:",
{
widget: "javascriptLinks",
}
);

this.updateChatbotState(message);
};

updateChatbotState(message) {
// NOTICE: This function is set in the constructor, and is passed in from the top level Chatbot component. The setState function here actually manipulates the top level state of the Chatbot, so it's important that we make sure that we preserve the previous state.

this.setState((prevState) => ({
...prevState,
messages: [...prevState.messages, message],
}));
}
}

export default ActionProvider;

2.  We need to add this method as the handler in the

LearningOptions
component:

2.我们需要将此方法添加为

LearningOptions
组件中的处理程序:

import React from "react";

import "./LearningOptions.css";

const LearningOptions = (props) => {
const options = [
{
text: "Javascript",
handler: props.actionProvider.handleJavascriptList,
id: 1,
},
{ text: "Data visualization", handler: () => {}, id: 2 },
{ text: "APIs", handler: () => {}, id: 3 },
{ text: "Security", handler: () => {}, id: 4 },
{ text: "Interview prep", handler: () => {}, id: 5 },
];

const optionsMarkup = options.map((option) => (
<button
className="learning-option-button"
key={option.id}
onClick={option.handler}
>
{option.text}
</button>
));

return <div className="learning-options-container">{optionsMarkup}</div>;
};

export default LearningOptions;

Alright! That was quite a lot of information. But if we now try to click the JavaScript option in the chatbot, we get this result:

好的! 那是很多信息。 但是,如果现在尝试单击聊天机器人中JavaScript选项,则会得到以下结果:

Perfect. But we don't want to stop there, this is a chatbot after all. We want to be able to respond to users who want to use the input field as well. So we need to make a new rule in

MessageParser
.

完善。 但是我们不想到此为止,毕竟这是一个聊天机器人。 我们也希望能够对想要使用输入字段的用户做出回应。 因此,我们需要在

MessageParser
制定一个新规则。

Let's update our

MessageParser.js
file to look like this:

让我们将

MessageParser.js
文件更新为如下所示:

class MessageParser {
constructor(actionProvider) {
this.actionProvider = actionProvider;
}

parse(message) {
const lowerCaseMessage = message.toLowerCase();

if (lowerCaseMessage.includes("hello")) {
this.actionProvider.greet();
}

if (lowerCaseMessage.includes("javascript")) {
this.actionProvider.handleJavascriptList();
}
}
}

export default MessageParser;

Now try typing "javascript" into the input field and sending the message. You should get the same list in response from the chatbot.

现在尝试在输入字段中键入“ javascript”并发送消息。 您应该从聊天机器人获得相同的列表作为响应。

So there you have it. We've set up a chatbot that renders a list of possible options and responds to user input.

所以你有它。 我们已经设置了一个聊天机器人,该机器人呈现可能选项的列表并响应用户输入。

For now, we've only set up the bot to handle when someone clicks or types in JavaScript, but you can try to expand the other options on your own. Here's a link to the repository.

目前,我们仅将机器人设置为在有人单击或键入JavaScript时进行处理,但您可以尝试自行扩展其他选项。 这是到存储库的链接

All the code is on GitHub, so feel free to dive into the react-chatbot-kit code or docs.

所有代码都在GitHub上,因此请随时进入react-chatbot-kit代码或docs

结论 (Conclusion)

Building things is fun, and a great way to expand your skillset. There are no limits to where you could take this next.

建立事物很有趣,也是扩展技能的一种好方法。 接下来可以做什么没有限制。

Perhaps you could make a chatbot that finds the ideal product in webshop based on some simple questions (utilising routing in the app), or maybe you can make one for your company taking care of the most common customer inquiries.

也许您可以使一个聊天机器人根据一些简单的问题(在应用程序中使用路由)在网上商店中找到理想的产品,或者也许可以为您的公司制造一个最常见的客户查询服务。

Feel free to expand, come up with new ideas, and test them out. And if you see something that can be improved, send a pull request.

随时扩展,提出新想法并进行测试。 如果您发现可以改进的地方,请发送请求请求。

If you want to improve as a developer, I encourage you to keep building. It truly is the only path forward. If you enjoyed this article, and would like to know when I post more content, you can follow me on Twitter.

如果您想以开发人员的身份提高自己,我鼓励您继续努力。 这确实是前进的唯一途径。 如果您喜欢这篇文章,并且想知道我何时发布更多内容,可以在Twitter上关注我

翻译自: https://www.freecodecamp.org/news/how-to-build-a-chatbot-with-react/

react中使用构建缓存

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: