如何将JSON对象从子对象传递给父对象?

时间:2019-03-28 08:59:54

标签: javascript reactjs

我在子组件中有一个axios客户端,我从中接收数据-我正在尝试将JSON数据传递给父组件。

问题是我收到以下错误:

TypeError: Cannot read property 'props' of undefined at inputArea.js:69

inputArea.js:69是以下行:this.props.getUserResults(response.data);

这是我的父组件:

class App extends Component {

  getUserResults = (results) => {
    console.log(results);
  } 

  render() {
    return (
      <Container>
        <Headers />
        <InputArea getUserResults={this.getUserResults}>

        </InputArea>
        <UserResults>

        </UserResults>
      </Container>
    );
  }
}

export default App;

我的孩子部分:

export default class InputArea extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      draw_number: '',
      user_number_1: '',
      user_number_2: '',
      user_number_3: '',
      user_number_4: '',
      user_number_5: '',
      user_number_6: '',
    }
  }

  submitHandler = () => {
    let { draw_number, ...rest } = this.state;
    let results = {
      numbers: Object.keys(rest).map(key => parseInt(rest[key])),
      draws: parseInt(draw_number)
    };
    console.log(results);

    axios.post("http://localhost:8080/simulate/", results)
    .then(function(response) {
      this.props.getUserResults(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
  }

  inputHandler = event => this.setState({[event.target.name]: event.target.value});

  render() {
      return (
        <InputField>
          <InputWrapper>
            <Label>1st number</Label>
            <Input name="user_number_1" type="number" maxlength="2" value={this.state.user_number_1} onChange={this.inputHandler} required></Input>
            <Label>2nd number</Label>
            <Input name="user_number_2" type="number" maxlength="2" value={this.state.user_number_2} onChange={this.inputHandler} required></Input>
            <Label>3rd number</Label>
            <Input name="user_number_3" type="number" maxlength="2" value={this.state.user_number_3} onChange={this.inputHandler} required></Input>
            <Label>4th number</Label>
            <Input name="user_number_4" type="number" maxlength="2" value={this.state.user_number_4} onChange={this.inputHandler} required></Input>
            <Label>5th number</Label>
            <Input name="user_number_5" type="number" maxlength="2" value={this.state.user_number_5} onChange={this.inputHandler} required></Input>
            <Label>6th number</Label>
            <Input name="user_number_6" type="number" maxlength="2" value={this.state.user_number_6} onChange={this.inputHandler} required></Input>
            <Label>Number of draws:</Label>
            <Input name="draw_number" type="number" value={this.state.draw_number} onChange={this.inputHandler} required></Input>
          </InputWrapper>
          <Button type="button" onClick={this.submitHandler}>Let's win!</Button>
        </InputField>
      )
  }
}

0 个答案:

没有答案