更改道具时更新反应根组件

时间:2019-10-20 10:49:54

标签: reactjs

我有一个react / redux应用程序,它已作为第三方窗口小部件嵌入到其他网页中。

应用程序从其嵌入页面上的窗口对象接收配置对象。 示例配置对象可以是:

window.appConfig = {
    color: 'blue'
}

当配置对象的属性更改时,我希望能够更新应用程序。

我无法控制父页面何时/是否更改配置对象-在某些情况下,加载页面后异步更新配置对象。

道具更新时,根组件的componentDidUpdate()是否有办法触发,或者如何监听更新的道具?

index.js文件如下所示:

ReactDOM.render(
    <Provider store={store}>
      <App config={window.appConfig} />
    </Provider>,
    window.document.getElementById("root")
)

app.js文件如下所示:

class App extends React.Component {

    // This is not called when config object change
    componentDidUpdate(prevProps) {
        console.log(this.props)
    }

  render() {
    return <pre>{JSON.stringify(this.props, null, 2)}</pre>
  }
}

...

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App)

(检测更改的一种怪异方法是设置时间间隔并检查config对象的更改,但我想避免这种情况)

1 个答案:

答案 0 :(得分:1)

相反,将config的值放在痛处,并将connect的组件放置在redux商店中,并在配置更新时dispatch从商店中进行更改,它将正常工作

// config.js
import store from '../path/to/store'

const updateConfig = (config)=>{
  store.dispatch({
    type:"APP_CONFIG_UPDATE", // add a reducer to catch this and updates it
    payload:config
  })
}
// use the `updateConfig` when change

在应用程序上,只需从redux状态解构配置

  

注意:   您可以使用功能组件代替类,它会根据道具的变化而更新,而无需类的生命周期

或:

const updateConfig = (config)=>{
  store.dispatch({
    type:"APP_CONFIG_UPDATE", // add a reducer to catch this and updates it
    payload:config
  })
}

setInterval(()=>{
   const {getState} = store
   cosnt { config } = getState()
  if(compareObjects(window.appConfig,config))
    updateConfig(window.appConfig)

},1000 * 60 /* each minute */)

// for simple object comparisons 
function compareObjects = (obj1,obj2)=>JSON.stringify(obj1) === JSON.stringify(obj2)