简体   繁体   English

更新状态后,react 组件不会重新渲染

[英]react component does not rerender after update state

I have this react functional component where I have file input .我有这个反应功能组件,我有文件输入。 after I choose the file I assume the text in h1 tag should convert from choose file to test but nothing happen在我选择文件后,我假设 h1 标签中的文本应该从choose file转换为test但没有任何反应

  • the handleChange function gets fired handleChange 函数被触发
  • the console.log print state.show : true console.log 打印 state.show : true
  • the INSIDE console.log() print state.show : true but does not show the string test INSIDE console.log() 打印 state.show : true 但不显示字符串测试
import React, { useState } from 'react';

export default ({ selectedFile }) => {
  const [state, setState] = useState({});

  const handleChange = e => {
    console.log('in handleChange');
    setState({ ...state, show: true });
  };
  console.log('My state: ', state);
  return (
    <div className='file-uploader'>
      <input type='file' id='upload' hidden onChange={handleChange} />
      <label htmlFor='upload'>
        {state.show ? <h1> {console.log('INSIDE ', state)} test</h1> : <h1>choose file</h1>}
      </label>
    </div>
  );
};

You need the following property {show: false} in your initial state.在初始状态下,您需要以下属性{show: false}

import React, { useState } from 'react';

export default ({ selectedFile }) => {
  const [state, setState] = useState({show: false});

  const handleChange = e => {
    console.log('in handleChange');
    setState({ ...state, show: true });
  };
  console.log('My state: ', state);
  return (
    <div className='file-uploader'>
      <input type='file' id='upload' hidden onChange={handleChange} />
      <label htmlFor='upload'>
        {state.show ? <h1>test</h1> : <h1>choose file</h1>}
      </label>
    </div>
  );
};

Live Demo现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM