React子组件不会重新呈现状态更改

时间:2017-05-06 13:06:43

标签: reactjs ecmascript-6 jsx axios rerender

我有一个返回其他组件的Tasks组件。但是,当我从Tasks组件更改其中一个子组件的状态时,它不会重新呈现。

我将'newTaskAdded'状态从父项传递给子项作为props并将其分配给子状态以重新呈现子组件,但它仍然没有发生。

我的目标是: 当用户添加任务时,我希望它立即显示在屏幕上,这意味着用户必须刷新页面才能看到新任务。

Tasks.jsx:

import React , { Component } from 'react'
import axios from 'axios'
import Name from './Name.jsx'
import ShowTasks from './ShowTasks.jsx'

class Tasks extends Component {
  constructor(props) {
    super(props)
    this.state={
      task: '',
      newTaskAdded:false,
      newTask:[],
    }
    this.handleChange = this.handleChange.bind(this)
    this.addTask = this.addTask.bind(this)
  }
  handleChange(event) {
    this.setState({task: event.target.value})
  }
  addTask() {
    axios.post('/api/addtask',{
      name:this.props.name,
      task:this.state.task
    })
    .then((res) => {
      if(res.status=='200'){
        this.setState ({task:''})
        this.setState ({newTaskAdded:true})
        this.setState ({newTask: res.data.message[res.data.message.length-1] })
      }
    })
    .catch((err) => {
      if(err) throw err
    })
  }

  render() {
    return (
      <div>
        <div>
          <Name name={this.props.name} />
        </div>
        <div>
          <input value={this.state.task} onChange={this.handleChange} type="text" name="task" />
          <button type="button" onClick={this.addTask}>Add Task</button>
        </div>
        <ShowTasks name={this.props.name} updated={this.state.newTaskAdded} />
      </div>
    )
  }
}

export default Tasks

ShowTasks.jsx

import React , { Component } from 'react'
import axios from 'axios'
import Completed from './Completed.jsx'
import NotCompleted from './NotCompleted.jsx'

class ShowTasks extends Component {
  constructor(props) {
    super(props)
    this.state = {
      tasks:[],
      updated:this.props.updated
    }
  }
  componentWillMount(){
    axios.post('/api/loadtasks', {
      name: this.props.name
    })
    .then((res) => {
      console.log('res', res);
      this.setState ({tasks:res.data.tasks})
    })
    .catch((err) => {
      throw err
    })
  }
  render() {
    return (
      <div className='pointer'>
        {this.state.tasks.map((task) => {
          if(task.completed) {
            return <Completed key={task._id} {...task} />
          }
          else {
            return <NotCompleted key={task._id} {...task} />
          }
        })}
      </div>
    )
  }
}

export default ShowTasks

2 个答案:

答案 0 :(得分:1)

所以问题出在你的子函数中,你要将props设置为state,

您在构造函数中将props设置为state,并且每次props更改时都不会调用构造函数,而只会在组件呈现时第一次调用,因此状态不会使用正确的值进行更新。

您应该在componentWillReceiveProps函数中设置props,该函数在父组件的每个渲染上调用

class ShowTasks extends Component {
  constructor(props) {
    super(props)
    this.state = {
      tasks:[],
      updated:this.props.updated
    }
  }
  componentWillReceiveProps(nextProps) {
      this.setState({updated: nextProps.updated});
  }
  componentWillMount(){
    axios.post('/api/loadtasks', {
      name: this.props.name
    })
    .then((res) => {
      console.log('res', res);
      this.setState ({tasks:res.data.tasks})
    })
    .catch((err) => {
      throw err
    })
  }
  render() {
    return (
      <div className='pointer'>
        {this.state.tasks.map((task) => {
          if(task.completed) {
            return <Completed key={task._id} {...task} />
          }
          else {
            return <NotCompleted key={task._id} {...task} />
          }
        })}
      </div>
    )
  }
}

export default ShowTasks

详细了解生命周期功能以及何时使用 here:

答案 1 :(得分:0)

OK!解决:

Tasks.jsx:

import React , { Component } from 'react'
import axios from 'axios'
import Name from './Name.jsx'
import ShowTasks from './ShowTasks.jsx'

class Tasks extends Component {
  constructor(props) {
    super(props)
    this.state={
      user:this.props.user,
      task:'',
      newTask:[],
    }
    this.handleChange = this.handleChange.bind(this)
    this.addTask = this.addTask.bind(this)
  }

  handleChange(event) {
    this.setState({task: event.target.value})
  }

  addTask() {
    axios.post('/api/addtask',{
      name:this.state.user.name,
      task:this.state.task
    })
    .then((res) => {
      if(res.status=='200'){
        this.setState ({user:this.state.user})
        this.setState ({newTask: res.data.message[res.data.message.length-1] })
      }
    })
    .catch((err) => {
      if(err) throw err
    })
  }

  render() {
    return (
      <div>
        <div>
          <Name name={this.props.user.name} />
        </div>
        <div>
          <input value={this.state.task} onChange={this.handleChange} type="text" name="task" />
          <button type="button" onClick={this.addTask}>Add Task</button>
        </div>
        <ShowTasks user={this.state.user}/>
      </div>
    )
  }
}

export default Tasks

ShowTasks.jsx:

import React , { Component } from 'react'
import axios from 'axios'
import Completed from './Completed.jsx'
import NotCompleted from './NotCompleted.jsx'

class ShowTasks extends Component {
  constructor(props) {
    super(props)
    this.state = {
      user: this.props.user,
      tasks:[],
    }
    this.loadTasks=this.loadTasks.bind(this)
  }

  loadTasks() {
    axios.post('/api/loadtasks', {
      name: this.state.user.name
    })
    .then((res) => {
      this.setState ({tasks:res.data.tasks})
    })
    .catch((err) => {
      throw err
    })
  }

  componentWillReceiveProps(nextProps) {
    this.loadTasks()
  }

  render() {
    return (
      <div className='pointer'>
        {this.state.tasks.map((task) => {
          if(task.completed) {
            return <Completed key={task._id} {...task} />
          }
          else {
            return <NotCompleted key={task._id} {...task} />
          }
        })}
      </div>
    )
  }
}

export default ShowTasks