【发布时间】:2020-08-15 23:43:28
【问题描述】:
我从过去两周开始学习 React。目前我正在学习 Stephen Grider 的 Udemy 课程。 我正在构建一个类似于 twitch 的虚拟流媒体平台,我可以在其中创建、删除、编辑和观看流媒体。
现在我正在编写 StreamDelete 组件,该组件将显示一个模式,用户可以在其中删除特定流或取消。
这是我写的代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React from "react";
import Modal from "../modal";
import history from "../../history";
import { connect } from "react-redux";
import { fetchIndividualStream } from "../../actions";
class streamDelete extends React.Component {
componentDidMount() {
this.props.fetchIndividualStream(this.props.match.params.id);
}
action = () => {
return (
<React.Fragment>
<button className="ui button negative">Delete</button>
<button className="ui button">Cancel</button>
</React.Fragment>
);
};
renderContent = () => {
return `Are you sure you want to delete : ${
this.props.streams
? this.props.streams[this.props.match.params.id].title
: ""
}`;
};
render() {
return (
<Modal
title="Delete Stream"
content={this.renderContent()}
action={this.action()}
onDismiss={() => history.push("/")}
/>
);
}
}
const mapStateToProps = (state) => {
return { stream: state.streams };
};
export default connect(mapStateToProps, {
fetchIndividualStream,
})(streamDelete);
这里 fetchIndividualStream 操作将获取要从 API 中删除的流并将其存储在状态中。
此操作后的 redux store 如下所示
输出应该是什么:
当组件第一次渲染状态为 null 以及成功获取流时,模式将出现。唯一的区别是成功获取后标题将显示在“您确定要删除:”之后。请参阅renderContent 方法。
我的问题是,即使在状态像第一张图像一样更新后,模态也不显示标题。我不知道这个问题,但是在更改一些代码时它起作用了。
我所做的更改是在 mapStateToProps 和 renderContent 方法中。
mapStateToProps
const mapStateToProps = (state, ownProps) => {
return { stream: state.streams[ownProps.match.params.id] };
};
renderContent 方法:
renderContent = () => {
return `Are you sure you want to delete : ${
this.props.stream ? this.props.stream.title : ""
}`;
};
【问题讨论】:
-
你需要从 react-router-dom 导入的
withRouter
标签: javascript reactjs