Javascript Redux将初始状态设置为API响应
我正在创建一个网站来展示一些手机,并设置了一个API来从我的数据库中传回最新的手机。在componentWillMount中的我的组件中,我正在调度一个操作,然后该操作将获取API结果并填充我的存储。然后,组件渲染存储中的内容 这看起来一切正常,但确实意味着在API调用进行时,有时什么都没有显示 我想知道是否有某种方法可以在服务器上分派操作并将initialState设置为API响应,或者有其他方法将API响应从服务器传递到客户端,以便在组件呈现时数据已经存在 这就是我目前所拥有的 还原剂 行动 Server.jsJavascript Redux将初始状态设置为API响应,javascript,reactjs,redux,store,Javascript,Reactjs,Redux,Store,我正在创建一个网站来展示一些手机,并设置了一个API来从我的数据库中传回最新的手机。在componentWillMount中的我的组件中,我正在调度一个操作,然后该操作将获取API结果并填充我的存储。然后,组件渲染存储中的内容 这看起来一切正常,但确实意味着在API调用进行时,有时什么都没有显示 我想知道是否有某种方法可以在服务器上分派操作并将initialState设置为API响应,或者有其他方法将API响应从服务器传递到客户端,以便在组件呈现时数据已经存在 这就是我目前所拥有的 还原剂 行动
非常感谢您的帮助 如果要在您所在的客户机上渲染React,则在组件渲染之前,无法预加载数据@刘先生的上述评论是正确的。。。最好的选择是在提取数据时呈现加载微调器或其他等效对象
或者,可以使用服务器端渲染。这意味着提前呈现React并向客户端提供HTML文件。通过在服务器上渲染,您可以从数据库中获取所需的数据,并在渲染之前将其作为道具传递给组件。不需要AJAX,而且您永远不必向客户端显示加载视图。由于它是异步的,因此无法保证您可以在加载组件之前将数据保存在那里,你最好只是有一个加载屏幕,并在数据加载时更新加载屏幕。是的,我在我的网站上有API请求的其他地方也这样做过,但是我希望有一种方法可以传递正确的初始状态,在这种情况下,不需要用户交互,这样Google也可以为SEO目的抓取内容。你有什么好的教程或服务器端渲染示例推荐吗?我觉得这对我来说可能更有用,因为我希望有内容加载的SEO好处。
export function latestPhonesHasErrored(state = false, action) {
switch (action.type) {
case 'LATEST_PHONES_HAS_ERRORED':
return action.latestPhonesHasErrored;
default:
return state;
}
}
export function latestPhonesIsLoading(state = false, action) {
switch (action.type) {
case 'LATEST_PHONES_IS_LOADING':
return action.latestPhonesIsLoading;
default:
return state;
}
}
export function latestPhones(state = [], action) {
switch (action.type) {
case 'LATEST_PHONES_FETCH_DATA_SUCCESS':
return action.latestPhones;
default:
return state;
}
}
export function latestPhonesFetchData() {
return (dispatch) => {
dispatch(latestPhonesIsLoading(true));
fetch('/api/latest-phones/')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(latestPhonesIsLoading(false));
return response;
})
.then((response) => response.json())
.then((results) =>
dispatch(latestPhonesFetchDataSuccess(results)))
.catch(() => dispatch(latestPhonesHasErrored(true)))
}
}
const store = createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
);
const router = express.Router();
router.get('/', (req, res) => {
match({routes, location: req.originalUrl}, (err, redirectLocation, renderProps) => {
if(!err) {
const html = this.render(renderProps);
res.render('index', {
content: html,
pageTitle: 'title',
description: 'description',
canonical: 'canonical'
});
} else {
res.status(500).send();
}
});
});
render(renderProps) {
let html = renderToString(
<Provider store={store}>
<RouterContext {...renderProps}/>
</Provider>
);
return html;
}
import {latestPhonesFetchData} from '../../../actions/results-actions';
const mapStateToProps = (state) => {
return {
latestPhones: state.latestPhones
}
};
class Home extends Component {
componentWillMount(){
this.props.latestPhonesFetchData();
}
render(){
/* all component render here*/
}
}
export default connect(mapStateToProps, {latestPhonesFetchData})(Home);