javascript - 如何制作 React 组件构造...?
问题描述
没有在渲染方法中实际使用它?
我有一个 React 组件,它只包含逻辑,但仍然使用来自 redux 的 dispatch()。它被称为F1_Start
// import F1_Start from './F1_Start'
如何让这个文件运行?
我试过了
new F1_Start()
但这似乎不起作用。
我最终会将它放在一个简单的 JavaScript 类中,但我仍然需要访问dispatch()
实际文件
import React from 'react';
import { connect } from 'react-redux';
class F1_Start extends React.Component {
constructor(props) {
super(props);
this.fetchData();
}
fetchData = () => {
const options = {
credentials: 'include'
};
fetch("/api/items", options)
.then((response) => {
return response.json();
})
.then((results) => {
this.props.dispatch({type: 'updateBookmarks', bookmarks: results});
this.findStatus(results);
})
.catch((err) => {
this.notLoggedIn();
console.log('DEBUG: fetch /api/items error');
});
}
findStatus = (results) => {
if(results[results.length - 1].id_google){
const user = results.slice(-1);
this.loggedIn(user);
} else {
this.notLoggedIn();
}
}
notLoggedIn = () => {
window.setTimeout(() => {
// this.props.dispatch({ type: 'updateMenu', current: 'splash' });
}, 4000);
window.setTimeout(() => {
// this.props.dispatch({ type: 'toggleSideBar' });
}, 8000);
}
loggedIn = (user) => {
this.props.dispatch({ type: 'setUser', current: user[0] });
}
}
export default connect()(F1_Start);
解决方案
您可以创建一个普通类 F1_Start 并在父组件 ParentComponent 中调用其方法,您的普通类可以返回适当的操作,您可以从父连接组件调度这些操作。这样,您可以将服务逻辑分开。下面是我能想出的代码。
注意:此代码未经测试,您需要根据需要进行更改。
class ParentComponent extends React.Component{
constructor() {
this.fecthingData()
}
fecthingData() {
let f1_Start = new F1_Start();
f1_Start.fetchData().then(actions => {
actions.forEach(action => {
this.props.dispatch(action);
});
})
}
}
export default connect()(ParentComponent);
class F1_Start {
fetchData () {
const actions = [];
const options = {
credentials: 'include'
};
return fetch("/api/items", options)
.then((response) => {
return response.json();
})
.then((results) => {
actions.push ({ type: 'updateBookmarks', bookmarks: results });
actions.push(this.findStatus(results));
return actions;
})
.catch((err) => {
console.log('DEBUG: fetch /api/items error');
actions.push(this.notLoggedIn());
return actions;
});
}
findStatus (results) {
if (results[results.length - 1].id_google) {
const user = results.slice(-1);
return this.loggedIn(user);
} else {
return this.notLoggedIn();
}
}
notLoggedIn() {
return { type: 'updateMenu', current: 'splash' };
}
loggedIn(user){
return { type: 'setUser', current: user[0] };
}
}
export default F1_Start;
推荐阅读
- amazon-web-services - AWS 是否支持 Oracle 自治数据库?
- go - 乘以 *float32 和 int 值
- joomla - 错误:无法启动应用程序:在 joomla 中找不到类“JSessionHandlerJoomla”
- javascript - Javascript恢复部分字符串不起作用?
- c# - “当前上下文中不存在名称‘fieldname’的原因
- java - 如何将变量值传递给套接字字符串
- julia - 有没有办法将我的函数转换为Julia中DifferentialEquations.jl中的标准ODE函数?
- nginx - 使用 caddy 或 nginx 时,如何让代理忽略 url 前缀?
- laravel - 限制从 Laravel 通知外观发送到 Slack 的消息
- java - Java:在方法中使用更少的代码拆分字符串