我正在尝试featherjs 和nextjs。现在不知何故,我可以使用 nextjs SSR 从服务器获取初始数据,并使用 feathersjs 订阅我的 api。
我现在真的不知道为什么它会起作用以及这里到底发生了什么。也许有人对此有更好的实施?还是我以错误的方式使用这些库?
这个想法是让组件呈现在第一次加载时由服务器呈现的初始道具,然后对于下一个请求,使用 observable 来获取状态。
这是我的书籍页面代码。它只显示书籍列表:
import React from 'react';
import Main from '../layouts/Main';
import client from '../scripts/feathers-client';
const clientService = client.service('api/books');
export default class Books extends React.Component {
constructor (props) {
super(props);
if (this.props && this.props.books) {
this.state = {books: this.props.books};
} else {
this.obs = clientService.watch().find().subscribe(books => {
this.setState({books: books});
});
}
}
static async getInitialProps ({ req }) {
if (req) {
let service = req.app ? req.app.service('api/books') : {};
return { books: await service.find() };
} else {
return { books: ''};
}
}
componentWillUnmount () {
if (this.obs) {
this.obs.unsubscribe();
}
}
render () {
const renderBooks = this.state ?
<ol>
{this.state.books.data.map(book => (
<li key={book._id}>{book.author}, {book.title}, liked: {book.liked}<p>{book.synopsis}</p></li>
))}
</ol>
:
'';
return (
<Main>
<p>List of books :</p>
{renderBooks}
</Main>
);
}
}
任何帮助,将不胜感激。