我使用的是React v15.3.2,Redux和React-refetch v1.0.0-beta.10,我想在呈现页面之前获取数据。在我的代码下面:
布局组件
/* Import libraries */
export default class extends Component {
...
render() {
return (
<Provider store={ this.store }>
{ this.renderComponent() }
// In this case, I would render User component(see code below)
</Provider>
)
}
}
用户组件
import React from 'react'
import {connect, PromiseState} from 'react-refetch'
import Layout from 'layout'
class User extends Layout {
renderComponent() {
const {userFetch} = this.props;
if (userFetch.pending) {
return <p>Pending</p>
} else if (userFetch.rejected) {
return <p>Rejected</p>
} else if (userFetch.fulfilled) {
return <p>Fulfilled</p>
}
}
}
export default connect(props => ({
userFetch: `https://jsonplaceholder.typicode.com/users`
}))(User)
当我运行服务器时,我收到此错误:Invariant Violation: fetch must be a function. Instead received a undefined.
您能否告诉我我做错了什么?
PS :当我将静态数据放入renderComponent
并将export default connect...
更新为export default User
时,它就可以了!
解决方案:
1 - 在User
组件中,将<ListUsers />
放在renderComponent()
2 - 安装isomorphic-fetch
并添加ListUsers
作为组件:
// Import librairies
require('isomorphic-fetch');
class ListUsers extends Component {
// Put the body of renderComponent() here
}
export default connect(...)
我不知道它是否是最佳解决方案,但它对我有用。
答案 0 :(得分:-2)
export default connect(props => ({
userFetch: `https://jsonplaceholder.typicode.com/users`
}))(User)
我认为您的代码中存在错误:它不应该是:
export default connect(props) => ({
userFetch: `https://jsonplaceholder.typicode.com/users`
})(User)
看看我如何移动括号?