gpt4 book ai didi

javascript - 仅在单击时分派(dispatch)到 Prop

转载 作者:行者123 更新时间:2023-12-01 01:27:34 25 4
gpt4 key购买 nike

我遇到的问题是,mapDispatchToProps 是作为一个整体发送的,我希望它仅在我单击删除按钮时才发送。

这是我的类,它获取 fetchList 很好,一切都按预期工作,但是当我添加删除按钮时,它似乎把一切搞乱了,它似乎为页面上的每次刷新调用删除,任何知道为什么吗?

这可能是我创建 Buttonrender() 吗?也许我没有点击它就会触发它?只需创建列表即可,因为每次通过 map 创建每个 itemInList 时都会触发它。

class List extends Component {
componentWillMount() {
this.props.fetchList();
}

componentWillReceiveProps(nextProps) {
if (nextProps.newItem) {
this.props.list.unshift(nextProps.newItem);
}
}

onDelete = (id) => {
this.props.deleteItem(id);
}

render() {
const listItems = this.props.list.map(itemInList => (
<div key={itemInList.id}>
<h3 className="title__font smaller">{itemInList.title}
<Button
btnType="Delete"
onClick={this.onDelete(itemInList.id)}>
<i className="fas fa-trash-alt"></i>
</Button>
</h3>
<p className="body__font">{itemInList.body}</p>
</div>
));
return (
<div>
<h1 className="title__font">List</h1>
{ listItems }
</div>
);
};
};

List.propTypes = {
fetchList: PropTypes.func.isRequired,
list: PropTypes.array.isRequired,
newItem: PropTypes.object
};

const mapStateToProps = state => ({
list: state.list.items,
newItem: state.list.item
});

const mapDispatchToProps = dispatch => {
return {
fetchList: () => dispatch( actions.fetchList() ),
deleteItem: (id) => dispatch( actions.deleteItem(id) )
};
};

export default connect(mapStateToProps, mapDispatchToProps)(List);

这是删除项目的操作:

export const deleteItem = (id) => dispatch => {
console.log(id);
dispatch({
type: actionTypes.DELETE_ITEM,
payload: filtered
})
};

该日志在操作文件中被触发 10 次。

最佳答案

您需要将函数声明传递到 onClick你需要通过id以某种方式。由于性能问题,我们不想在渲染方法中声明任何函数,但我们需要某种方法来传递 id进入调用时的方法。数据属性是解决这个问题的一个很好的方法。

这是一些相关文档。

首先,确保this方法的上下文绑定(bind)到组件,如下所示:

constructor(props) {
super(prop)

this.onDelete = this.onDelete.bind(this)
}

上述内容是必需的,因为类方法实际上是在其原型(prototype)上定义的,而不是在单独的实例化上定义的。旁注:如果您使用的构建系统具有类似于 babel-plugin-proposal-class-properties 的内容,您可以按如下方式声明您的方法:

onDelete = (e) => { this.props.deleteItem(e.target.dataset.id) }

您需要更新您的onDelete方法如下:

onDelete = (e) => {
this.props.deleteItem(e.target.dataset.id);
}

您还需要更新 Button渲染方法中的标记如下所示:

<Button
btnType="Delete"
data-id={itemInList.id}
onClick={this.onDelete}
>
<i className="fas fa-trash-alt"></i>
</Button>

编辑:

这是一个工作 Code Sandbox展示这一切是如何运作的。我必须对您的代码进行一些更改,例如排除未包含的 <Button/>成分。我希望这可以帮助您到达您需要到达的地方。

关于javascript - 仅在单击时分派(dispatch)到 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53619242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com