簡體   English   中英

重新渲染具有更新更改的組件

[英]Re render a component with updated changes

我有一個 Home 組件,它從數據庫中獲取數據並顯示它。

import React, {Component} from 'react';
import { Jumbotron,Modal,Button,ModalHeader,ModalBody,
Form,FormGroup,Input,Label} from 'reactstrap';
import { Card, CardTitle, CardText, Row, Col } from 'reactstrap';
import {   CardHeader, CardFooter, CardBody } from 'reactstrap';
import axios from 'axios';
import BlogAddForm from './BlogAddForm';
import NavbarComponent from './NavbarComponent';

 class HomeComponent extends Component{
 constructor(){
 super();
 this.state={
  isSignupModalOpen:false,
  isLoginModalOpen:false,
  isblogOpen:false,
  blogs:[]
  }

this.toggleSignupModal=this.toggleSignupModal.bind(this);
this.toggleLoginModal=this.toggleLoginModal.bind(this);
this.toggleblogModal=this.toggleblogModal.bind(this);

 }

componentDidMount() {
console.log("component did mount");
axios.get('http://localhost:3000/')
.then(response => {
  if (response.data.length > 0) {
    this.setState({ 
      blogs: response.data
    });
  }
 })
 .catch((error) => {
  console.log(error);
})


}




 toggleSignupModal(){
  this.setState({
  isSignupModalOpen:!this.state.isSignupModalOpen
  })
  }

  toggleLoginModal(){
  this.setState({
  isLoginModalOpen:!this.state.isLoginModalOpen
  })
  }

 toggleblogModal(){
 this.setState({
  isblogOpen:!this.state.isblogOpen
  })
 }


  render(){
   console.log("inside render ");

  var b=this.state.blogs.map((blog)=>{
    console.log(blog);
     var taggu=blog.tags.map((tag)=>{
      return(
        <span>#{tag}</span>
      )
      });
    var con=blog.content.slice(0,100);
    return(
      <Col className="my-1" lg="4" sm="6" >
      <Card key={blog._id}>
          <CardHeader tag="h3">{blog.topic}</CardHeader>
          <CardBody>
            <CardTitle tag="h5">By {blog.writer.username}</CardTitle>
            <CardText>{con}... </CardText>
            <Button>Learn More</Button>
          </CardBody>
          <CardFooter>{taggu}</CardFooter>
        </Card>
      </Col>
     )
  });


   return (
  
    <div className="App">
  
    <NavbarComponent />
    <Jumbotron>
      <h1 className="display-5">WELCOME TO BLOGERA</h1>
      <p className="lead">This is a simple blog site where you can put your thoughts into words and 
       interact with people.</p>
      <p className="my-2">
        <Button color="success" onClick={this.toggleblogModal}>Add Blog</Button>
      </p>
    </Jumbotron>
    {b}
    <Modal isOpen={this.state.isLoginModalOpen} toggle={this.toggleLoginModal}>
                <ModalHeader  toggle={this.toggleLoginModal}>Login</ModalHeader>
                <ModalBody>
                    <Form onSubmit={this.handleLogin}>
                        <FormGroup>
                            <Label htmlFor="username">Username</Label>
                            <Input type="text" id="username" name="username" innerRef= 
                   {(input)=>this.username=input}/>
                        </FormGroup>
                        <FormGroup>
                            <Label htmlFor="password">Password</Label>
                            <Input type="password" id="password" name="password" innerRef= 
                    {(input)=>this.password=input} />
                        </FormGroup>
                        <FormGroup check>
                            <Label check>
                                <Input type="checkbox" name="remember" innerRef= 
                    {(input)=>this.remember=input}/>
                                Remember me
                            </Label>
                        </FormGroup>
                        <Button type="submit" value="submit" color="primary">Login</Button>
                    </Form>
                </ModalBody>
            </Modal>

    <Modal isOpen={this.state.isSignupModalOpen} toggle={this.toggleSignupModal}>
                <ModalHeader  toggle={this.toggleSignupModal}>Signup</ModalHeader>
                <ModalBody>
                    <Form onSubmit={this.handleLogin}>
                        <FormGroup>
                            <Label htmlFor="username">Username</Label>
                            <Input type="text" id="username" name="username" innerRef= 
                     {(input)=>this.username=input}/>
                        </FormGroup>
                        <FormGroup>
                            <Label htmlFor="password">Password</Label>
                            <Input type="password" id="password" name="password" innerRef= 
                       {(input)=>this.password=input} />
                        </FormGroup>
                        <FormGroup check>
                            <Label check>
                                <Input type="checkbox" name="remember" innerRef= 
                             {(input)=>this.remember=input}/>
                                Remember me
                            </Label>
                        </FormGroup>
                        <Button type="submit" value="submit" color="primary">Signup</Button>
                    </Form>
                </ModalBody>
            </Modal>


    <Modal isOpen={this.state.isblogOpen} toggle={this.toggleblogModal}>
                <ModalHeader  toggle={this.toggleblogModal}>Write Blog</ModalHeader>
                <ModalBody>
                    <BlogAddForm toggleblogModal={this.toggleblogModal} />
                </ModalBody>
            </Modal>

   

    <Row>
     <Col className="my-1" lg="4" sm="6" >
    <Card>
    <CardHeader tag="h3">Header</CardHeader>
    <CardBody>
      <CardTitle tag="h5">Special Title Treatment</CardTitle>
      <CardText>With supporting text below as a natural lead-in to additional content.</CardText>
      <Button>Learn More</Button>
    </CardBody>
    <CardFooter>Footer</CardFooter>
  </Card>
   </Col>

  <Col className="my-1" lg="4" sm="6" >
  <Card>
    <CardHeader tag="h3">Featured</CardHeader>
    <CardBody>
      <CardTitle tag="h5">Special Title Treatment</CardTitle>
      <CardText>With supporting text below as a natural lead-in to additional content.</CardText>
      <Button>Learn More</Button>
    </CardBody>
    <CardFooter className="text-muted">Footer</CardFooter>
  </Card>
  </Col>

  <Col className="my-1" lg="4" sm="6" >
  <Card>
    <CardHeader tag="h3">Featured</CardHeader>
    <CardBody>
      <CardTitle tag="h5">Special Title Treatment</CardTitle>
      <CardText>With supporting text below as a natural lead-in to additional content.</CardText>
      <Button>Learn More</Button>
    </CardBody>
    <CardFooter className="text-muted">Footer</CardFooter>
  </Card>
  </Col>

</Row>

  
</div>
 );
  }
  }


 export default HomeComponent;

BLOGADDFORM 是一個在后端獲取數據並發送 post 請求的組件。 我希望隨着數據庫的更新,我的 homecomponent 應該使用更新的數據重新呈現。 我嘗試重定向到我的主組件,但這並沒有解決目的。 這是我的博客添加表單組件

 import React, {Component} from 'react';
 import { Button,Form,FormGroup,Input,Label} from 'reactstrap';
 import  { Redirect } from 'react-router-dom';
 import axios from 'axios';


 class BlogAddForm extends Component{
  constructor(){
  super();
  this.state = {
    input: {},
    errors: {}
  };

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

  handleChange(event) {
    let input = this.state.input;
    input[event.target.name] = event.target.value;
  
    this.setState({
      input:input
    });
   }

  handleSubmit(event) {
    event.preventDefault();
  
    if(this.validate()){
        console.log(this.state);
        axios.post("http://localhost:3000/nb", {
             params:{
                 data:this.state.input
             }
        }).then((res)=>{
          let input = {};
        input["topic"] = "";
        input["content"] = "";
        input["tag"] = "";

        this.setState({input:input});
  
        alert('Blog Added');
        this.props.toggleblogModal();
        <Redirect to='/' />
        }).catch((err)=>{
          console.log(err);
        })
        
    }
   }

    validate(){
    let input = this.state.input;
    let errors = {};
    let isValid = true;

    if (!input["topic"]) {
      isValid = false;
      errors["topic"] = "Please enter the topic of blog.";
    }

    if (!input["content"]) {
      isValid = false;
      errors["content"] = "Please write some content.";
    }



    if (!input["tag"]) {
      isValid = false;
      errors["tag"] = "Please enter tags related to this blog.";
    }

    this.setState({
      errors: errors
    });

    return isValid;
    }
     render(){
    return(
        <Form onSubmit={this.handleSubmit}>
        <FormGroup>
        <Label htmlFor="topic">Topic</Label>
            <Input type="text" id="topic" name="topic"  
            value={this.state.input.topic}
          onChange={this.handleChange}
          />
          <div className="text-danger">{this.state.errors.topic}</div>
        </FormGroup>
        <FormGroup>
            <Label htmlFor="content">Content</Label>
            <Input type="textarea" id="content" name="content" rows={8} 
             value={this.state.input.content}
             onChange={this.handleChange}
             />
             <div className="text-danger">{this.state.errors.content}</div>
        </FormGroup>
        <FormGroup>
            <Label htmlFor="tag">Tags</Label>
            <Input type="text" id="tag" name="tag" 
             value={this.state.input.tag}
            onChange={this.handleChange}
             />
            <div className="text-danger">{this.state.errors.tag}</div>
        </FormGroup>
    
        <Button type="submit" value="submit" color="primary">Submit</Button>
    </Form>
    )
    }
     }
      export default BlogAddForm;

重新進入 Home 組件視圖時,您需要使用componentDidUpdate()

將您的網絡請求提取到不同的 function 並從componentDidMount()componentDidUpdate()調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM