我有一个使用React的Meteor应用程序 . 我添加了Session变量,并希望将新的Session值(将是另一个React组件)传递到另一个react组件中 .
用户将单击SideNav中的p-tag并将会话重置为React组件 .
SideNav component :
import React from 'react';
import { Session } from 'meteor/session';
import SonataContent from './sonata-content';
export default () => {
injectSonataText = () => {
const sonataContent = <SonataContent/>;
Session.set('MainContent', sonataContent); /* Set Session value to component */
};
return (
<div className="side-nav">
<h2>Explore</h2>
<p onClick={this.injectSonataText.bind(this)}><i className="material-icons">child_care</i><span> Sonatas</span></p>
</div>
)
}
在MainWindow中,Tracker.autorun重新运行并将状态设置为组件并呈现新的状态值 .
Main Window component:
import React from 'react';
import { Session } from 'meteor/session';
import { Tracker } from 'meteor/tracker';
export default class MainWindow extends React.Component {
constructor(props) {
super(props);
this.state = {
text: ""
}
}
componentDidMount() {
this.mainWindowTracker = Tracker.autorun(() => {
const text = Session.get('MainContent');
this.setState({text: text});
});
}
componentWillUnmount() {
this.mainWindowTracker.stop();
}
render() {
return (
<p>{this.state.text}</p>
)
}
}
我收到错误“不变违规:对象作为React孩子无效” . 这是由setState中使用的组件引起的吗?有没有办法做到这一点?
1 回答
Session set function接受一个值EJSON-able Object,我认为它可能不适用于React Object .
不过我会尝试(虽然只是猜测):
...