Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法获取要更新的组件_Javascript_Reactjs - Fatal编程技术网

Javascript 无法获取要更新的组件

Javascript 无法获取要更新的组件,javascript,reactjs,Javascript,Reactjs,我试图在调用fetch()时更新页面上的一个区域,该调用带有fetch()调用产生的错误消息。提交表单按钮时执行fetch()调用 当fetch()完成时,我已经编写了ErrorMessage(数据['Result'])我认为它会将数据['Result']作为道具传递。您可以在我的渲染中看到,我有,我认为这将使用fetch()调用中的消息进行更新 请参阅下面我的完整代码以了解此页面: import React from 'react'; import './css/LoginForm.css';

我试图在调用
fetch()
时更新页面上的一个区域,该调用带有
fetch()
调用产生的错误消息。提交表单按钮时执行
fetch()
调用

fetch()
完成时,我已经编写了
ErrorMessage(数据['Result'])我认为它会将
数据['Result']
作为
道具传递。您可以在我的渲染中看到,我有
,我认为这将使用
fetch()
调用中的消息进行更新

请参阅下面我的完整代码以了解此页面:

import React from 'react';
import './css/LoginForm.css';

function ErrorMessage(props) {
    return (
        <p id="error-message">
            {props.error}      
        </p>
    )
}

class LoginForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: ''
        };

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleInputChange(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    }

    handleSubmit(event) {
        event.preventDefault();
        var loginData = {
            username: this.state.username,
            password: this.state.password
        }

        fetch('/login', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                loginData: loginData
            })
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            if (data['Result']) {
                console.log(data['Result']);
                ErrorMessage(data['Result']);
            }
        })
        .catch(function(error) {
            console.log('Error: ', error);
        });
    }

    render() {
        return (
            <div id="login-form-container">
                <form id="login-form" onSubmit={this.handleSubmit} method="POST">
                    <ErrorMessage error="Original Message" />
                    <input
                        type="text"
                        name="username"
                        placeholder="username"
                        autoComplete="username"
                        onFocus={(e) => e.target.placeholder = ''}
                        onBlur={(e) => e.target.placeholder = 'username'}
                        value={this.state.username}
                        onChange={this.handleInputChange}
                        required
                    ></input>
                    <input
                        type="password"
                        name="password"
                        placeholder="password"
                        autoComplete="current-password"
                        onFocus={(e) => e.target.placeholder = ''}
                        onBlur={(e) => e.target.placeholder = 'password'}
                        value={this.state.password}
                        onChange={this.handleInputChange}
                        required
                    ></input>
                    <button type="submit" name="submit">Login</button>
                    <p className="forgotten-password">Forgotten your password?</p>
                </form>
            </div>
        );
    }

}

export default LoginForm;
从“React”导入React;
导入“./css/LoginForm.css”;
函数错误消息(props){
返回(

{props.error}

) } 类LoginForm扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 用户名:“”, 密码:“” }; this.handleInputChange=this.handleInputChange.bind(this); this.handleSubmit=this.handleSubmit.bind(this); } handleInputChange(事件){ const target=event.target; 常量值=target.value; const name=target.name; 这是我的国家({ [名称]:值 }); } handleSubmit(事件){ event.preventDefault(); var Loginda={ 用户名:this.state.username, 密码:this.state.password } 获取(“/login”{ 方法:“POST”, 标题:{ “接受”:“应用程序/json”, “内容类型”:“应用程序/json” }, 正文:JSON.stringify({ 罗吉娜达:罗吉娜达 }) }) .然后(功能(响应){ 返回response.json(); }) .then(功能(数据){ 如果(数据['Result']){ 日志(数据['Result']); 错误消息(数据['Result']); } }) .catch(函数(错误){ console.log('Error:',Error); }); } render(){ 返回( e、 target.placeholder='''} onBlur={(e)=>e.target.placeholder='username'} 值={this.state.username} onChange={this.handleInputChange} 必修的 > e、 target.placeholder='''} onBlur={(e)=>e.target.placeholder='password'} 值={this.state.password} onChange={this.handleInputChange} 必修的 > 登录

忘记密码了吗

); } } 导出默认登录信息;

这可能是完全错误的,因为我正努力理解ReactJS中的组件是如何工作的,所以我提前道歉。感谢您的帮助。

获取
完成时创建组件不会影响
登录表单
组件的
呈现
方法返回的内容

您可以改为在
LoginForm
状态中设置错误消息,并将其用作呈现方法中
ErrorMessage
组件的道具

示例

class LoginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: "",
      error: "Original Message"
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  // ...

  handleSubmit(event) {
    event.preventDefault();
    var loginData = {
      username: this.state.username,
      password: this.state.password
    };

    fetch("/login", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        loginData: loginData
      })
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        if (data["Result"]) {
          console.log(data["Result"]);
          this.setState({ error: data["Result"] });
        }
      })
      .catch((error) => {
        console.log("Error: ", error);
      });
  }

  render() {
    return (
      <div id="login-form-container">
        <form id="login-form" onSubmit={this.handleSubmit} method="POST">
          <ErrorMessage error={this.state.error} />
          <input
            type="text"
            name="username"
            placeholder="username"
            autoComplete="username"
            onFocus={e => (e.target.placeholder = "")}
            onBlur={e => (e.target.placeholder = "username")}
            value={this.state.username}
            onChange={this.handleInputChange}
            required
          />
          <input
            type="password"
            name="password"
            placeholder="password"
            autoComplete="current-password"
            onFocus={e => (e.target.placeholder = "")}
            onBlur={e => (e.target.placeholder = "password")}
            value={this.state.password}
            onChange={this.handleInputChange}
            required
          />
          <button type="submit" name="submit">
            Login
          </button>
          <p className="forgotten-password">Forgotten your password?</p>
        </form>
      </div>
    );
  }
}
类LoginForm扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
用户名:“”,
密码:“”,
错误:“原始消息”
};
this.handleInputChange=this.handleInputChange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
}
// ...
handleSubmit(事件){
event.preventDefault();
var Loginda={
用户名:this.state.username,
密码:this.state.password
};
获取(“/login”{
方法:“张贴”,
标题:{
接受:“应用程序/json”,
“内容类型”:“应用程序/json”
},
正文:JSON.stringify({
罗吉娜达:罗吉娜达
})
})
。然后((响应)=>{
返回response.json();
})
。然后((数据)=>{
如果(数据[“结果”]){
console.log(数据[“结果”]);
this.setState({error:data[“Result”]});
}
})
.catch((错误)=>{
日志(“错误:”,错误);
});
}
render(){
返回(
(e.target.placeholder=“”)}
onBlur={e=>(e.target.placeholder=“username”)}
值={this.state.username}
onChange={this.handleInputChange}
必修的
/>
(e.target.placeholder=“”)}
onBlur={e=>(e.target.placeholder=“password”)}
值={this.state.password}
onChange={this.handleInputChange}
必修的
/>
登录

忘记密码了吗

); } }
非常感谢,但是我在控制台中收到了这样的消息:
Error:TypeError:无法读取未定义的
this.setState({Error:data[“Result”]})的属性'setState'@Matt啊,对不起。我没有注意到
函数
用于
然后
的函数。我将它改为箭头函数(
()=>{…}
),这样
这个
将是您所期望的。