当我水合已经存在的成分时,它会重新呈现。问题是没有状态。因此,依赖状态的代码段将重新呈现,并因此被破坏。
我正在服务器上使用renderToString来提供一个HTML文件,该文件提供一个可以捆绑根节点的bundle.js。在我renderToString之前,我从数据库中获取数据并将其提供给呈现为字符串的组件。
来自服务器文件。使用快递
// ...
app.get('*', (req, res) => {
fs.readFile('./public/index.html', 'utf-8', (err, file) => {
if(err) {
res.status(400).send(err);
}
database.getReviews(1234, (err, data) => {
if (err) {
res.status(400).json({message: err});
return;
}
const html = renderer(file, data);
res.send(html);
});
});
});
// ...
带有渲染器功能的模块
import React from "react";
import ReactDOM from "react-dom/server";
import App from "../client/components/App.jsx";
export default function renderer(html, data) {
const serverHtml = ReactDOM.renderToString(<App data={data} />);
const regex = /(<div id="reviews">)(<\/div>)/;
html = html.replace(regex, function(original, div1, div2) {
return div1 + serverHtml + div2;
});
return html;
}
具有水合功能的索引文件
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.hydrate(<App />, document.getElementById('reviews'));
App.js,这是我继承的旧版代码
import React from 'react';
import Reviews from './reviews';
import ReviewModal from './reviewModal';
import styled from 'styled-components';
const ModalProp = styled.div`
&&& {
opacity: ${props => props.isModalShowing ? "0.5" : "1.0"};
}
`;
class App extends React.Component {
static formatDate(date) {
// ...
}
constructor(props) {
super(props);
this.state = {
reviews: this.props.data,
isModalShowing: false,
isModalSelected: false
};
this.toggleModal = this.toggleModal.bind(this);
this.selectModal = this.selectModal.bind(this);
}
componentWillMount(){
console.log(this.props)
// debugger;
}
toggleModal() {
this.setState({
isModalShowing: !this.state.isModalShowing,
isModalSelected: false
});
}
selectModal() {
this.setState({
isModalSelected: true
});
}
render() {
return (
<div className="Reviews">
<div id="rApp">
<div className="rBodyContainer">
<div className="rModalContainer">
<ReviewModal
id="modal"
isModalShowing={this.state.isModalShowing}
isModalSelected={this.state.isModalSelected}
selectModal={this.selectModal}
toggleModal={this.toggleModal}
reviews={this.state.reviews}
formatDate={App.formatDate}
/>
</div>
<div
className="rPageContainer"
onClick={this.toggleModal}
>
<ModalProp isModalShowing={this.state.isModalShowing}>
<hr />
<div className="rPaddingTop">
<h1 className="rReviewTitle">Reviews</h1>
<Reviews
isModalShowing={this.state.isModalShowing}
toggleModal={this.toggleModal}
reviews={this.state.reviews}
formatDate={App.formatDate}
/>
<div className="rModalButtonContainer">
<a
className="rMoreReviews"
id="moreReviews"
style={{ 'color': '#914669' }}
onClick={this.toggleModal}
>
Read all {this.state.reviews.length} reviews
</a>
</div>
</div>
</ModalProp>
</div>
<hr />
</div>
</div>
</div>
);
}
}
export default App;
我希望水合物可以附加事件监听器,以更新“ isModalShowing”和“ isModalSelected”状态,从而重新呈现模式