【问题标题】:How to send response to react after dispatching action调度动作后如何发送响应以做出反应
【发布时间】:2021-08-26 14:27:34
【问题描述】:

我有一张带有立即购买按钮的桌子

<tr>
<td>some more  </td>
         <td>
         <button
              className="btn btn-primary btn-success"
              id="buy-now"
              type="button" onClick={ e => onClick(data) }
            >
              <i className="fa fa-check" />
            </button>
          </td>
</tr>

因此,当它单击时,它将所有 tr 数据发送到 additemtobuy 下面从 action.js redux 导入的函数

const table = () => { 
const onClick = (data) => {
additemtobuy(data)
}
return({
the above table data
})
}

在 action.js 中

export default const additemtobuy = (data) => { 

//perform some axios operation and add the items to user order table
 await axios.post('/api/order',data)
 .then( res => { 
console.log('items bought')
/*
I can use dispatch to change the state but I want to show some response on the buy now button 
I used state to change the state of the buy now using redux dispatch but it changes the state of all buy-now buttons 
*/

  })

}

任何人都可以帮助我,任何建议都会有所帮助

【问题讨论】:

  • 您的问题到底是什么? data 可能是 { data } 吗?如果这是来自服务器的错误,您是否有 catch 来显示您收到的错误? data 在到达您的onClick 函数时是已定义还是未定义?
  • NO 我的命令执行成功,我可以调度函数,但我想在所有这些之后在按钮单击中显示一些响应

标签: javascript node.js reactjs redux axios


【解决方案1】:

您应该识别具有唯一 ID 的按钮。例如,如果您在 table 组件内创建本地状态,则可以跟踪单击的按钮并使用 css 选择器 tr.clicked #buy-now 以不同的样式呈现它们。当然,使用clicked 状态,您不仅可以编辑类名,还可以编辑任何属性、属性等。


const table = () => { 
    const [clicked, setClicked] = React.useState({});
    const onClick = (data, id) => { 
        additemtobuy(data);
        setClicked(c=>{
            c.id = true;
            return {...c};
        })
    }
    return(
            <tr className={clicked['some-identifier'] ? 'clicked' : '' }>
            <td>some more  </td>
            <td>
            <button
                className="btn btn-primary btn-success"
                id="buy-now"
                type="button" onClick={ e => onClick(data, 'some-identifier') }
                >
                <i className="fa fa-check" />
                </button>
            </td>
    </tr>
    ) 
}


你的特殊风格

tr.clicked #buy-now {
  background-color: red;
}

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 2022-10-20
    • 2018-03-14
    • 1970-01-01
    • 2020-07-17
    • 2019-10-07
    • 2021-07-11
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多