我正在try 制作一个很好的ApiWrapper组件来填充各个子组件中的数据.从我读到的所有信息来看,这应该有效:https://jsfiddle.net/vinniejames/m1mesp6z/1/

class ApiWrapper extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      response: {
        "title": 'nothing fetched yet'
      }
    };
  }

  componentDidMount() {
    this._makeApiCall(this.props.endpoint);
  }

  _makeApiCall(endpoint) {
    fetch(endpoint).then(function(response) {
      this.setState({
        response: response
      });
    }.bind(this))
  }

  render() {
    return <Child data = {
      this.state.response
    }
    />;
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: props.data
    };
  }

  render() {
    console.log(this.state.data, 'new data');
    return ( < span > {
      this.state.data.title
    } < /span>);
  };
}

var element = < ApiWrapper endpoint = "https://jsonplaceholder.typicode.com/posts/1" / > ;

ReactDOM.render(
  element,
  document.getElementById('container')
);

但出于某种原因,当父组件状态发生变化时,子组件似乎没有更新.

我错过什么了吗?

推荐答案

你的代码有两个问题.

子组件的初始状态是通过props 设置的.

this.state = {
  data: props.data
};

引用这SO Answer句话:

将初始状态作为prop传递给组件是一种反模式

因此,如果你无法避免这种情况,理想的解决方案是使用方法componentWillReceiveProps来聆听新props .

将以下代码添加到子组件将解决子组件重新渲染的问题.

componentWillReceiveProps(nextProps) {
  this.setState({ data: nextProps.data });  
}

第二个问题与fetch有关.

_makeApiCall(endpoint) {
  fetch(endpoint)
    .then((response) => response.json())   // ----> you missed this part
    .then((response) => this.setState({ response }));
}

这是一把小提琴:https://jsfiddle.net/o8b04mLy/

Reactjs相关问答推荐

react-hook-form问题:为什么getValues不返回大多数当前值?

关于同一位置的不同组件实例的react S规则被视为相同组件

GoLang有条件地为.js.gz提供服务(如果它存在),否则为.js

GitHub页面未正确显示Reaction应用程序网站

React js拖放图像并预览

useEffect 和 ReactStrictMode

React-router动态路径

提前输入错误:选项类型上不存在属性名称

Spring Boot + React + MySQL应用的架构层面有哪些?

React - 函数组件 - 点击两次问题处理

React 组件列表中的第一个计时器正在获取值 NaN

带有 webpack 错误多个文件匹配路由名称的 Expo-router.无法Bundle 或部署应用程序

状态链接未传递到路由页面

Material UI v5.11 - Prop sx 在响应式中写了两次

antd 找不到 comments

在 Spring Cloud Gateway 中运行的 React SPA 页面刷新出现白标错误

更新和删除功能不工作 Asp.net MVC React

需要帮助在 document.queryselector 的 nextjs 页面上插入 useEffect 状态

React 检测哪些 props 在 useEffect 触发器上发生了变化

列表应该有一个唯一的关键props