DOM未更新,尽管函数更改了

时间:2019-05-28 01:56:21

标签: reactjs jsx

即使变量值更改为将导致元素无法呈现的值,页面也不会更新,并且元素仍然呈现。

试图在组件内部移动,没有用。

function clickHandler(item)
    {
    object[item].active = 0;
    }

let object = [{data: 
              <p onClick={() => clickHandler(0)}> Data </p>, 
              active:1},
              {data:
              <p onClick={() => clickHandler(1)}> Data2 </p>, 
              active:1}
             ];                                             


class Objects extends React.Component {
    constructor(props) {
        super(props);
    }


render() {
   return (
    <div class="notifications">
    {object[0].active == 1 ? object[0].data : " "}
    {object[1].active == 1 ? object[1].data : " "}
    </div>
    );
  }
}

ReactDOM.render(<Objects />, document.querySelector('#object_display'));"

希望消失,但不会消失。

1 个答案:

答案 0 :(得分:1)

更改外部数据不会触发组件的更新。您需要更改传递给组件的props或保持组件内部状态的状态。

考虑一下:

// data declared outside the component; gets passed as a prop
// in the ReactDOM.render call below.
const data = [
  {
    title: "Object 1"
  },
  {
    title: "Object 2"
  },
  {
    title: "Object 3"
  },  
]

class Objects extends React.Component {
  // initial state; start with the first item
  state = {index: 0}
  
  // onClick handler
  switch = () => {
    // get the current index out of this.state
    const {index} = this.state;

    // get the number of items in data so
    // we can loop back to 0 when we get to
    // the last item
    const {data: {length}} = this.props;

    // increment the index, don't go beyond length
    const newIndex = (index + 1) % length;

    // calling setState triggers a re-render
    // with the new index value
    this.setState({index: newIndex});
  }
  
  render () {
    const {data} = this.props;
    const {index} = this.state;
    const item = data[index];
    
    return (
      <div onClick={this.switch}>{item.title} (Click for next item)</div>
    );
  }
}

// data passed as a prop
ReactDOM.render(<Objects data={data} />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app" />