reactjs - React 子组件不会重新渲染状态更改

标签 reactjs ecmascript-6 jsx axios rerender

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

我将“newTaskAdded”状态作为 props 从父级传递给子级,并将其分配给子级以重新渲染子组件,但它仍然没有发生。

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

任务.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

显示任务.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

最佳答案

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

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

您应该在 componentWillReceiveProps 函数中设置 Prop ,该函数在父组件的每次渲染时调用

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:

关于reactjs - React 子组件不会重新渲染状态更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820825/

相关文章:

javascript - 如何在 React 中添加两个 onClick 函数

javascript - 从 'react' 导入 * 作为 React; vs 从 'react' 导入 React;

javascript - 如何用 ES6 类模拟私有(private)作用域?

javascript - 使用 ES6 保存函数 mongoose

reactjs - 带有动态子列的 Ant 设计表

ReactJS 沿层次结构覆盖或编辑上下文

javascript - 允许用户从 0.5 到 5 打分

javascript - ReactDOM.render 预期最后一个可选的 `callback` 参数是一个函数

javascript - 我的 React 应用程序将我的图像的 URL 呈现为 url ('undefined' );

javascript - 使用另一个组件更新/刷新一个组件