简体   繁体   中英

Make imported object reactive in React.js

I have an object in mydata.js file:

const myData = {
 name: 'John',
 lastname: 'Smith'
}
export default myData

In React component I import that object and pass it in component via props and put in on a page

import myData from './mydata.js'
const ParentComponent = () => {
  return (
   <ChildComponent info={myData} />
  )
}

Then for example in another component, let's named it DataChanger I changed a field in myData object:

 import myData from './mydata.js'     
 const DataChanger = () => {

  const onChangeDataHandler = () => {
    myData.name = 'David'
  }
  return (
    <div>
      <button onClick={() => onChangeDataHandler()}>Data Changer</button>
    </div>
  )
}

In this case, when I click on the button and change a field, I don't have changes in Child Component via props. Is it possible to make myData reactive?

编辑精彩艾伦 v5ddf

 // You need to use state import initialData from './mydata.js' const ParentComponent = () => { const [myData, setMyData] = useState({ ...initialData }); const onChangeHandler = (newData) => { setMyData({ ...myData, ...newData }); }; return ( <> <ChildComponent info={myData} /> <DataChanger onChangeHandler={onChangeHandler} /> </> ); } // Then const DataChanger = (props) => { const onButtonClick = (event) => { const newData = { name: 'David' }; props.onChangeHandler(newData); }; return ( <div> <button onClick={onButtonClick}>Data Changer</button> </div> ); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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