在纯React中,我从服务器获取数据后在clickActive
函数中调用了getTodos
函数。
getTodos = () => {
const url = 'https://jsonplaceholder.typicode.com/todos';
const params = {
expand: 'createdBy, updatedBy'
};
axios({
method: 'GET',
url,
params
})
.then(res => {
this.setState({
todos: res.data
}, () => this.clickActive());
})
.catch(error => {
console.log(error);
});
};
clickActive = () => {
const activeTask = document.querySelector('.activeTask');
activeTask.click();
console.log('active')
};
如何在React + Redux中调用函数clickActive
?我在getTodos
文件夹中创建actions
动作。在Todos
组件中,它通过单击getTodos
按钮来调用此功能GET
。提取数据后如何调用clickActive
函数?我将clickActive
函数放在了helpers
文件中。我应该将clickActive
函数导入文件actions/index.js
吗?
预期效果:单击按钮GET
->通话功能getTodos
->通话功能clickActive
此处演示:https://stackblitz.com/edit/react-rk1evw?file=actions%2Findex.js
动作
import axios from 'axios';
export const GET_TODOS = 'GET_TODOS';
export const FETCH_SUCCESS = 'FETCH_SUCCESS';
export const FETCH_FAILURE = 'FETCH_FAILURE';
export const getTodos = () =>
dispatch => {
return axios({
url: 'https://jsonplaceholder.typicode.com/todos',
method: 'GET',
})
.then(({data})=> {
console.log(data);
dispatch({type: GET_TODOS, payload:{
data
}});
})
.catch(error => {
console.log(error);
dispatch({type: FETCH_FAILURE})
});
};
export const getTodo = () =>
dispatch => {
return axios({
url: 'https://jsonplaceholder.typicode.com/todos',
method: 'GET',
})
.then(({data})=> {
console.log(data);
dispatch({type: GET_TODOS, payload:{
data
}});
})
.catch(error => {
console.log(error);
dispatch({type: FETCH_FAILURE})
});
};
Todos
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {getTodos} from '../.././actions';
import { clickActive } from '../../helpers';
class Todos extends Component {
constructor(props){
super(props);
}
render() {
return (
<>
<button onClick={this.props.getTodos}>GET</button>
<ul>
{this.props.todos.map(todo => {
return <li key={todo.id}>
{todo.title}
</li>
})}
</ul>
<div className="active">Active</div>
</>
);
}
}
const mapStateToProps = state => {
const { todos } = state;
return {
todos
};
};
const mapDispatchToProps = dispatch => ({
getTodos: () => dispatch(getTodos())
});
export default connect(mapStateToProps, mapDispatchToProps)(Todos);
助手
export const clickActive = () => {
const activeTask = document.querySelector('.active');
activeTask.click();
console.log('click div');
};
答案 0 :(得分:1)
您的clickActive
函数是一个将与创建的DOM交互的函数,因此应在componentDidUpdate和componentDidMount(如果要使用钩子,或在useEffect钩子)中渲染后调用。
在componentDidMount / componentDidUpdate场景中,我建议在您的Todos
组件中添加这些生命周期方法:
componentDidMount() {
// call clickActive once after mount (but your todos are probably empty this time)
clickActive();
}
componentDidUpdate(prevProps) {
if (prevProps.todos !== this.props.todos) {
// call clickActive every time when todos is changed
// (i.e. it will be called when your asynchronous request change your redux state)
clickActive();
}
}