我正在构建一个非常简单的同构React / Redux应用程序,在我的一个容器中,我想加载用户的详细信息和他们的专辑列表。
服务器和客户端都可以正常工作,但我收到错误:
Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) iv data-reactid="2">Loading...</div></di
(server) iv data-reactid="2"><a href="/users" dat
我知道这是因为在加载时服务器和客户端可能不同,因为客户端需要更长的时间来获取数据。但是如何解决这个问题?
如果我删除了{!user}
返回,那么页面就不会呈现,我收到一条错误消息,指出{user.firstName}
不存在。
这是我的组件代码:
// IMPORT DEPENDENCIES
// ==============================================
import React, {Component, PropTypes} from 'react';
import {Link} from 'react-router';
import {connect} from 'react-redux';
import {getAlbumsByUserId} from '../../redux/album/albumActions';
import {getUser} from '../../redux/user/userActions';
// USER CONTAINER
// ==============================================
export class User extends Component {
static propTypes = {
getAlbumsByUserId: PropTypes.func,
getUser: PropTypes.func,
params: PropTypes.object,
user: PropTypes.object
};
static needs = [
getAlbumsByUserId,
getUser
];
componentWillMount () {
this.props.getAlbumsByUserId();
this.props.getUser();
}
render () {
const {albums, user} = this.props;
if (!user) {
return <div>Loading...</div>;
}
return (
<div>
<Link to='/users'>Back to users</Link>
<h1>User: {user.firstName} {user.lastName}</h1>
{albums &&
albums.map((album) =>
<div key={album.id}>
<h2>
<Link to={`/albums/${album.id}`}>
{album.title}
</Link>
</h2>
</div>
)
}
</div>
);
}
}
// MAPPINGS
// ==============================================
const mapStateToProps = ({albums, users}) => {
return {
albums: albums.list.items,
user: users.activeItem.item
};
};
const mapDispatchToProps = (dispatch, props) => {
return {
getAlbumsByUserId: () => { dispatch (getAlbumsByUserId(props.params)); },
getUser: () => { dispatch(getUser(props.params)); }
};
};
// EXPORT
// ==============================================
export default connect(mapStateToProps, mapDispatchToProps)(User);
static needs
告诉服务器在页面加载时需要执行哪些操作。
答案 0 :(得分:0)
似乎我需要使用ComponentDidMount
而不是ComponentWillMount
答案 1 :(得分:-1)
通常,在处理同构方式时,我们从服务器传递inital data
和索引文件,而不是使用ajax加载数据。
例如在我们的主HTML文件中,我们将有类似
<script>
var APP_PROPS = JSON.stringify(props);
</script>
并将此数据用于初始渲染。