gpt4 book ai didi

reactjs - React Context API,组件给出无效类型错误

转载 作者:行者123 更新时间:2023-12-03 13:47:31 27 4
gpt4 key购买 nike

这是我的 app.js

import React from 'react'      
import {Header} from './common/header.component';
import {View} from './components/main';

export const {Provider, Consumer} = React.createContext('hello');

export class App extends React.Component {
constructor(props) {
super(props);
this.state = {
auth: 'hello'
};
this.authState = this.authState.bind(this);
}
authState(value){
console.log(value);
if(!value){
return this.state.auth;
} else if(typeof value === 'object'){
this.setState(value);
}
}

render() {
return (
<div className="app">
<Header/>
<Provider value={this.state.auth}>
<View updateAuth={this.authState}/>
</Provider>
</div>
)
}
}

这是我的登录组件

import {Consumer} from '../main.js';                                                                     

export class Signin extends React.Component {
constructor(props) {
super(props)
this.state = {
userUsername: '',
userPassword: ''
};
console.log(this.props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(e) {
this.setState({
[e.target.name]: e.target.value
})
}

handleSubmit(e) {
e.preventDefault();
return signinApi({userUsername: this.state.userUsername, userPassword: this.state.userPassword}).then((data) => {
console.log(data);
this.props.updateAuth({
auth: data.data.data
});
this.props.history.push('/home')
}).catch((err)=>{
alert(err.message)
})
}

render() {
return (
<Consumer>
{auth => auth ? (<Redirect to='/'/>) : (
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.userUsername} name="userUsername"
onChange={this.handleChange}/>
<input type="password" value={this.state.userPassword} name="userPassword"
onChange={this.handleChange}/>
<input type="submit"/>
</form>
<Link to="/signup">Signup</Link>
</div>
)}
</Consumer>
)
}
}

因此,我在这里尝试做的是维护全局身份验证状态,以处理 protected 路由,如果已经记录,我想重定向到主页。

但是一旦我加载登录组件,React 就会抛出一个错误:类型无效。我似乎无法弄清楚,这里出了什么问题。

另外,我对 context API 的理解是否正确?

编辑:包括错误堆栈

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Signin`.
in Signin (created by Route)
in Route (created by View)
in Switch (created by View)
in View (created by App)
in div (created by App)
in App
in Router (created by BrowserRouter)
in BrowserRouter
vendor.js:1297:7

最佳答案

您安装了什么版本的react-dom?我遇到了同样的错误并通过安装react-dom 16.3.0修复了它,但是我的错误是在我使用Provider的地方。

关于reactjs - React Context API,组件给出无效类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49586014/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com