我正在使用基于create-react-app的react应用程序,该应用程序在开发服务器上运行良好,但是当我运行构建时,发生了一些事情,该应用程序无法正常工作。
我使用带有某些功能的HOC作为上下文,在上下文(HOC)中声明的功能不起作用,因为未声明该功能。
对于开发人员,一切正常,如果我在构建之前进行测试供我评论
this.getProducts();
在componentDidMount上,使用下一个函数的问题将继续前进。
有人可以帮助我吗?预先感谢。
const GlobalContext = React.createContext()
class GlobalProvider extends React.Component {
constructor(props) {
super(props)
this.loadingToggle = ( status = null, where = '' ) => {
// enable and disable loading
}
this.loginFunction = (e, utente_id, password) => {
// rest api login
}
this.logoutFunction = () => {
// logout
}
this.getProducts = () => {
this.forceUpdate();
this.loadingToggle(true, "getProducts");
// HERE THE PROBLEMS
var _this = this;
axios.post(Config.apiBaseUrl + '/users/products', {
token: localStorage.getItem('token')
})
.then( (response) => {
if (response.data.success !== true ){
// user not exist
}else{
// populate user data
// HERE I USE _this
}
})
.catch(function (error) {
// catch error
});
}
this.cartVariation = (id, qty, minQty = 0) => {
// cart action
}
this.sendOrder = (addressId) => {
// send order
}
this.state = {
isAuth: false,
loginFunction: this.loginFunction,
logoutFunction: this.logoutFunction,
cartVariation: this.cartVariation,
removeCart: this.removeCart,
cart: null,
forceUpdate: this.forceUpdate,
lastUpdate: new Date().getTime(),
cartCount: JSON.parse(localStorage.getItem("mf-cart")) !== null ? Object.keys( JSON.parse(localStorage.getItem("mf-cart"))).length : 0,
loadingToggle: this.loadingToggle,
loading: false,
store : {
mf_product_list : [],
mf_categories : [],
mf_users : [],
mf_users_formatted : [],
mf_backorders : [],
mf_backorders_list : [],
mf_address : []
},
sendOrder: this.sendOrder
}
}
componentDidMount () {
if (localStorage.getItem('token') !== null && localStorage.getItem('token-timestamp') !== null ){
this.setState({isAuth : true});
}
this.getProducts();
}
render() {
return (
<GlobalContext.Provider
value={{
isAuth: this.state.isAuth,
authToken: null,
loginFunction: this.state.loginFunction,
logoutFunction: this.state.logoutFunction,
cartVariation: this.state.cartVariation,
removeCart: this.state.removeCart,
cart: null,
forceUpdate: this.state.forceUpdate,
lastUpdate: this.state.lastUpdate,
cartCount: this.state.cartCount,
loading: this.state.loading,
store: this.state.store,
sendOrder: this.sendOrder
}}
>
{this.props.children}
</GlobalContext.Provider>
)
}
}
const GlobalConsumer = GlobalContext.Consumer
export { GlobalProvider, GlobalConsumer }
答案 0 :(得分:0)
从“类”属性更改函数绑定
this.getProducts = () => {
// ...
}
将其绑定到构造函数中(ES2015)
constructor(props) {
// ...
this.getProducts = this.getProducts.bind(this);
}
有关函数绑定的更多信息是here。