React (6 踩坑)

踩坑——React双向数据绑定

React (6 踩坑)_第1张图片

踩坑——React父子组件传值,父组件调用setstate子组件不更新

一个评论案例

父组件index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './css/index.css'
import Content from './js/Content';
import Form from './js/Form';
class App extends React.Component {
     
  constructor() {
     
    super()
    this.state = {
     
      List: [
        {
      id: 1, title: '葫芦娃', content: '葫芦娃葫芦娃葫芦娃葫芦娃葫芦娃葫芦娃葫芦娃葫芦娃' },
        {
      id: 2, title: '奥特曼', content: '奥特曼奥特曼奥特曼奥特曼奥特曼奥特曼奥特曼奥特曼' },
        {
      id: 3, title: '奥特曼', content: '奥特曼奥特曼奥特曼奥特曼奥特曼奥特曼奥特曼奥特曼' },
      ],
    }
    this.setdata = this.setdata.bind(this)
  }
  setdata (comment) {
     
    this.setState({
     
      List: [...this.state.List, comment]
    })
    console.log(this.state.List);
  }

  render () {
     
    return (
      <div className="box">
        <Form List={
     this.state.List} setdata={
     this.setdata} />
        <Content List={
     this.state.List} />
      </div>
    )
  }
}

ReactDOM.render(<App />,
  document.getElementById('root')
);

Content子组件

import React from 'react';

import '../css/index.css'
export default class Content extends React.Component {
     
  constructor(props) {
     
    super(props)
    this.state = {
     
      List: this.props.List
    }
  }
  //强制刷新state的数据
  componentWillReceiveProps (props, netxtProps) {
     
    this.setState({
     
      List: props.List
    })
  }
  render () {
     
    return (
      <div>
        {
     
          this.state.List.map(item => {
     
            return (
              <div className="boxchil4" key={
     item.id}>
                <p>{
     item.title}</p>
                <p>{
     item.content}</p>
              </div>
            )
          })
        }
      </div>
    )
  }
}

Form子组件

import React from 'react';

import '../css/index.css'
export default class Content extends React.Component {
     
  constructor(props) {
     
    super(props)
    this.state = {
     
      List: this.props.List
    }
  }
  //强制刷新state的数据
  componentWillReceiveProps (props, netxtProps) {
     
    this.setState({
     
      List: props.List
    })
  }
  render () {
     
    return (
      <div>
        {
     
          this.state.List.map(item => {
     
            return (
              <div className="boxchil4" key={
     item.id}>
                <p>{
     item.title}</p>
                <p>{
     item.content}</p>
              </div>
            )
          })
        }
      </div>
    )
  }
}

React (6 踩坑)_第2张图片
componentWillReceiveProps (nextProps)该方法当props发生变化时执行,初始化render时不执行,在这个回调函数里面,你可以根据属性的变化,通过调用this.setState()来更新你的组件状态,旧的属性还是可以通过this.props来获取,这里调用更新状态是安全的,并不会触发额外的render调用

你可能感兴趣的:(react)