react-chatbot-kit点击Got it按钮报错:initialAction未定义
问题排查与解决
错误原因
react-chatbot-kit 中,通过 config 配置的Widget组件(如你的Gotitbtn)不会作为ActionProvider的子元素(children),你之前在ActionProvider里通过React.Children.map给子元素挂载actions的方式,无法将函数传递到Widget组件中,导致props.actions为undefined,调用props.actions.initialAction()时自然会抛出“无法读取undefined的initialAction属性”的错误。
解决方案
通过React Context上下文机制,将ActionProvider中的动作函数传递给Widget组件,具体步骤如下:
1. 创建ActionContext上下文文件
新建ActionContext.js,用于创建共享上下文:
import React from 'react'; const ActionContext = React.createContext(); export default ActionContext;
2. 修改ActionProvider.js,通过Context提供actions
修改ActionProvider,使用Context.Provider将动作函数暴露给所有子组件(包括Widget):
import React from 'react'; import ActionContext from './ActionContext'; const ActionProvider = ({ createChatBotMessage, setState, children }) => { const initialAction = () => { const message = createChatBotMessage('Just type in your name to begin.'); setState((prev) => ({ ...prev, messages: [...prev.messages, message] })) } const updateState = (message, checker) => { setState((prev) => ({ ...prev, messages: [...prev.messages, message], checker, })) } // 封装所有需要暴露的动作 const actions = { initialAction, updateState }; return ( <ActionContext.Provider value={actions}> {children} </ActionContext.Provider> ); }; export default ActionProvider;
3. 修改Gotitbtn.js,通过Context获取并调用actions
在Gotitbtn中使用useContext获取上下文里的动作函数,替换原来的props调用方式:
import React, { useContext } from "react"; import "./gotitbtn.css"; import ActionContext from "./ActionContext"; export default function Gotitbtn() { const actions = useContext(ActionContext); const handleGotItClick = () => { actions.initialAction(); }; return ( <div className="gt_btn_main"> <button className="gt_btn_button" onClick={handleGotItClick}> Got it! </button> </div> ); }
4. 确认Chatbot组件配置(确保ActionProvider正确传入)
确保你的Chatbot组件正确使用了修改后的ActionProvider:
import Chatbot from "react-chatbot-kit"; import ActionProvider from "./ActionProvider"; import config from "./config"; function App() { return ( <div className="App"> <Chatbot config={config} actionProvider={ActionProvider} /> </div> ); } export default App;
完成以上修改后,点击「Got it」按钮就能正常调用initialAction函数,不会再出现报错。
内容的提问来源于stack exchange,提问作者Shyamansh Sharma
相关产品推荐
相关产品推荐

