如 redux -> https://redux.js.org/basics/usage-with-react 的官方文档所示,逻辑和预设必须捆绑在一起。
问题是 - 我们不能将它们分开以使我们的代码更清晰,这是真的吗?
例如来自官方 redux.js.org 文档的一些组件。所以,逻辑和预制放在一起,看起来不太好和清晰:
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'
let AddTodo = ({ dispatch }) => {
let input
return (
<div>
<form
onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addTodo(input.value))
input.value = ''
}}
>
<input
ref={node => {
input = node
}}
/>
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}
AddTodo = connect()(AddTodo)
export default AddTodo
PS我也看到了这个问题:Separatingpresentational and logic components react/redux,这不一样。
UPD:我将逻辑分为 onSubmit module和组件呈现。但是 > 现在我收到一个错误 -
TypeError: Cannot call a class as a function
:
/* 推介会 */
import React from 'react';
import { connect } from 'react-redux';
import AddTodo from '../../Actions/AddTodo'
import addTodo from '../../Modules/handleClick'
class AddTodos extends React.Component{
componentDidMount() {
console.log(addTodo()); // for test. Get "TypeError: Cannot call a class as a function"
}
render() {
return (
<form>
<input type="text" placeholder="Your text" />
<button type="submit">Add todos</button>
</form>
);
}
}
export default AddTodos;
/* 提交module */
import { connect } from 'react-redux';
import AddTodo from '../Actions/AddTodo'
let addTodo = ({ dispatch }) => {
if (document.readyState === 'complete') {
let form = document.querySelector('form');
form.addEventListener('submit', handleClick);
function handleClick(e) {
e.preventDefault();
let input = document.querySelector('input');
dispatch(AddTodo(input.value));
input.value = '';
}
}
}
addTodo = connect()(addTodo);
export default addTodo;