React Redux Watson Chatbot State Issue

问题描述 投票:0回答:1

我是新来的反应redux。我正在尝试使用react和redux创建一个基于watson的聊天机器人。我的nodejs后端链接到watson api工作正常。但是,我对如何在前端处理用户和机器人消息感到困惑?

在组件确实挂载时,我将操作发送到我的后端,然后我从Watson获得响应,并且相应地更新状态。第一次,我只向后端发送一个空字符串。当用户按下发送消息按钮时带有他的消息。行动再次被触发。我正在使用redux thunk来执行异步操作。当我从后端得到响应时,我发送了类型为“SEND_USER_MSG_TO_SOE”和有效负载的操作。现在我必须将先前的响应发送到后端以获得新的响应,该响应存储在状态+新输入文本中。

在我的reducer中,我正在做这样的事情[... state,action.payload]。现在它也覆盖了先前响应的输入值。你能解释一下吗?

我需要数组中的输入和输出消息。这样我就可以使用map并将其显示为列表。

另一件事,如果我不返回[... state,action.payload]并仅发送有效负载。然后我只留下了一个回应。如何使用先前的响应输入和输出创建数组?

我附上了响应图片。请指导我

Watson Backend Response Image

谢谢见面

reducer: 
export default (state = [], action) => {
  console.log('reducer payload ---> ', action.payload);

  switch(action.type) {
    case 'SEND_USER_MSG_TO_SOE':
      return [...state, action.payload]
    default:
      return state;
  }
}

export default combineReducers({
  watsonResponse: converReducer
})

action:
export const sendMessage = (userInput) => {
  return async (dispatch, getState) => {
    let response = null;
    if (userInput === undefined) {
      response = await axios.post('http://localhost:8014/message_in', userInput);
    } else {
      let newInput = [...getState().watsonResponse];
      newInput[newInput.length - 1].input.text = userInput;
      response = await axios.post('http://localhost:8014/message_in', newInput[newInput.length - 1]);
    }
    dispatch({
      type: "SEND_USER_MSG_TO_SOE",
      payload: response.data
    });
  }
} 
reactjs redux ibm-watson watson-assistant
1个回答
0
投票

这条线是一个问题

newInput[newInput.length - 1].input.text = userInput;

您正在使用用户输入覆盖数组中的最后一个条目。您可能需要push数组中的新项目。

© www.soinside.com 2019 - 2024. All rights reserved.