正如您在下面的代码中所看到的,我希望在loadContent()
中建立一个从ReactComponent
调用的ajax调用。在访问子方法时,可以使用refs
关键字。然而,当调用者和接收者之间的关系不是父和子关系时。如何访问react中的方法?
ComponentA
这是一个全局组件,它将其功能与所需的所有其他响应组件共享。
import $ from 'jquery';
class ComponentA {
loadContent() {
$.ajax({
type: "POST",
url: "xxxx",
success: function(data) {
// Update the content of ReactComponent.
callToThatReactComponent.setContent(data); //Here is the problem
}
});
}
}
var compA = new ComponentA();
export default compA;
ReactCompoment
import React from 'react';
import ComponentA from 'path/to/ComponentA'; // The global module
export default class ReactComponent extends React.Component {
constructor(props) {
super(props);
ComponentA.loadContent();
}
setContent(_content) {
this.setState({
content: _content
});
}
}
发布于 2016-12-26 03:28:59
学习Redux和Thunks。去掉您拥有的这个全局组件。您正在尝试重新创建一个州管理系统,如通量或还原,但做错了。
行动档案:
const loadContent = () => {
return (dispatch, getState) => {
$.ajax({
type: "POST",
url: "xxxx",
success: function(data) {
// Update the content of ReactComponent.
dispatch({ type: 'LOAD_CONTENT_SUCCESS', data });
}
});
}
};
减速机档案:
任何没有副作用的函数逻辑(比如api调用或Math.Random())都会出现在这里。
const reducer = (state={}, action) => {
switch(action.type) {
case "LOAD_CONTENT_SUCCESS":
return {
...state,
action.data
};
}
}
任何组件文件:
使用mapStateToProps
可以让我们访问商店中的任何数据。
const mapStateToProps = (state) => ({
data: state.data
});
export default connect(mapStateToProps)(
class extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div>{this.props.data}</div>
}
}
)
发布于 2016-12-25 10:20:45
您可以在ComponentA中使用回调来完成这一任务。
class ComponentA {
loadContent( update ) {
$.ajax({
type: "POST",
url: "xxxx",
success: function(data) {
// Update the content.
update(data);
}
});
}
}
在ReactCompoment中:
ComponentA.loadContent( content => {
this.setState({ content: content}) }
);
https://stackoverflow.com/questions/41323412
复制