現在、私はEste.jsを発見しており、同型アプリに少し問題があります。renderToString() でサーバー側をレンダリングする前に API 呼び出しを行う方法がわかりません。
1 つの解決策は、React Router を使用してルーター レベルですべてのデータ取得を行うことです。最上位のルートに応じて、どのデータが必要になるかを予測し、API 呼び出しを行ってから、React.renderToString を呼び出すことができます。
素晴らしいですが、コンポーネント レベルとルーター レベルでデータの依存関係を宣言する必要があります。同じコードを 2 回書くことになり、それが最善の方法だとは思えません。
編集:わかりました、今のところ、私はやりたいことがいくらかできます。React-Router とこのリンクを使用して、次のことができました。
このグローバルなアプリの状態を指定して、/todos を指すときに todos をプリフェッチしたい
初期状態.js
{
auth: {
data: null,
form: null
},
examples: {
editable: {
state: null,
text: 'Some inline-editable text.'
}
},
i18n: {
formats: {},
locales: initialLocale,
messages: messages[initialLocale]
},
pendingActions: {},
todos: {
editables: {},
newTodo: {
title: ''
},
list: [{
id: 1,
title: 'first todo yipiyo'
}]
},
users: {
viewer: null
}
}
todos.react.js
todo コンポーネントで、静的関数 fetchData を宣言します。appState で正しいキーを取得したいので、「list」をパラメーターとして渡します。汚い感じ。
class Todos extends Component {
static fetchData(){
return actions.loadAllTodos('list');
}
componentDidMount(){
Todos.fetchData();
}
render() {
...
}
}
アクション.js
Api 呼び出しなど、キーを promise に渡します - ハックしているように感じます
export function loadAllTodos(key) {
const promise = new Promise((resolve, reject) => {
Api.get()
.then(res => {
res.key = key; //hacky time
resolve(res)
})
.catch(err => {
reject(err);
})
});
return dispatch(loadAllTodos, promise);
}
render.js
router.run((Handler, routerState) => {
var promise = Promise.all(routerState.routes
.filter(route => route.handler.fetchData)
.map(route => {
return route.handler.fetchData();
})
);
promise.then(resp => {
console.log(resp);
//Displays :
[ { id: 2, title: 'Im a second todo' },{ id: 3, title: 'I like todo' },
cursor: 'list' ]
//Some stuff to add resp to appState, using the correct key, yey iso+api=win
appState = mergeThisWithMagic(appState, resp);
const html = preloadAppStateThenRenderHtml(Handler, appState);
const notFound = routerState.routes.some(route => route.name ===
'not-found');
const status = notFound ? 404 : 200;
res.status(status).send(html);
resolve();
});
});
ご覧のとおり、更新された todoList で appState を更新する関数を作成します。
このすべてを実行しても問題ありませんか? 暗い道を進んでいるように感じるので、フィードバックをお願いします:(。