简体   繁体   中英

React: show data from api on the same page, when you click button

I have laravel project with react. i have questions and answers with eloquent. 在此处输入图像描述

everything works fine, except when i click on 'run query' button, I want data to be printed on the page. I solved logic in controller and have a endpoint in postman where it shows data from eloquent query. all i need is to print it when button is clicked. I tried following. Here in the end, I have solutions:

class Qindex extends React.Component {

constructor(){
    super()
    this.state = {
        questions:[],
        newQuestionData:{
          title:"",
          solution:""
        },
        editQuestionData:{
          id:"",
          title:"",
          solution:""
        },
        newQuestionModal:false,
        editQuestionModal:false,
        solutions:[]
    }
}

here is my function

getSolution(id) {
        axios.get('http://127.0.0.1:8000/api/questions/' + id + '/solution').then((response) => {
            this.setState({
                solutions: response.data
            })
        })
    }

and here is render, last button is what i need and i tried something but when i click it page just turns blank:

render(){

    let questions = this.state.questions.map((question) => {
        return(
            <tr key={question.id}>
                <td>{question.id}</td>
                <td>{question.title}</td>
                <td>{question.solution}</td>
                <td>
                    <Button color="success" size="sm" className="mr-2"
                            onClick={this.editQuestion.bind(this, question.id, question.title, question.solution)}
                    >Edit</Button>

                    <Button color="danger" size="sm"
                            onClick={this.deleteQuestion.bind(this, question.id)}
                    >Delete</Button>

                    <Button color="primary" size="sm"
                            onClick={this.getSolution.bind(this, question.id)}
                    >Run query</Button>
                    <p>{this.state.solutions.map((solution) =>(
                        {solution}
                    ))}</p>
                </td>
            </tr>
        )
    })

How can I get and print data correctly on button click? You can check my whole component here

You're not returning anything in the render().

render() {
 return this.state.questions.map((question) => {
   return (
        <tr key={question.id}>
          // rest of the code
        </tr>
     )
    });
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM