如果道具发生变化,React 原生组件不会重新渲染



如果 props 更改,我的组件不会更新,但调度的操作是正确的,存储更新正确。 反应生命周期方法没有听道具。

只有在状态发生更改时,才重新渲染组件。 但是shouldComponentUpdate((,getDerivedStateFromProps(( 和componentDidUpdate((并没有意识到 props 发生了变化。

如果道具发生变化,如何重新渲染组件?

元件:

import React, { Component } from 'react';
import { StyleSheet, View, Text, TextInput, TouchableOpacity } from 'react-native';
export default class Main extends Component {
constructor(props) {
super(props);
this.state = {
todos: []
};
}
addTodo() {
this.props.addTodo(this.state.title)
}
render() {
return (
<View>
<Text style={style.title} >Alma</Text>
<TextInput style={style.input} placeholder="New todo title" placeholderTextColor="gray" onChangeText={(text) => this.setState({ title: text })} />
<TouchableOpacity style={{ margin: 20, backgroundColor: "lightblue", padding: 15, borderRadius: 20 }} onPress={() => this.addTodo()} >
<View>
<Text>Send</Text>
</View>
</TouchableOpacity>
{
this.props.todos.map((e, i) => {
return (
<Text style={{ textAlign: "center", fontSize: 17, margin: 10 }} key={i} >{e.title}</Text>
)
})
}
</View>
);
}
}
const style = StyleSheet.create({
title: {
textAlign: "center",
marginTop: "20%",
fontSize: 20
},
input: {
borderColor: "black",
borderWidth: 2,
borderRadius: 20,
paddingVertical: 10,
paddingHorizontal: 20,
color: "black"
}
})
import { connect } from 'react-redux'
import { addTodo } from "./reducer";
import Main from "./Main";
function mapStateToProps(state, props) {
return {
todos: state.todos
}
}
function mapDispatchToProps(dispatch, props) {
return {
addTodo: (text) => dispatch(addTodo(text))
}
}
const MainContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Main)
export default MainContainer;

减速机和动作:

export default function todoReducer(state = { todos: [] }, action) {
if (action.type === 'ADD_TODO') {
let currentState = state;
currentState.todos.push(action.newTodo);
return currentState;
}
return state
}
export function addTodo(title) {
return {
type: "ADD_TODO",
newTodo: title
}
}

并存储:

import { createStore } from 'redux';
import todoReducer from "./reducer";
import { composeWithDevTools } from "redux-devtools-extension";

export default store = createStore(todoReducer,composeWithDevTools());

你正在改变化简器中的状态,使用 currentState.todos.push(action.newTodo(,它应该是一个纯函数,否则 react 无法知道 props 发生了变化。

将化简器函数更新为纯函数

export default function todoReducer(state = { todos: [] }, action) {
if (action.type === 'ADD_TODO') {
const todos = [...state.todos, action.newTodo];
return {...state, todos };
}
return state;
}

最新更新